MYSQL LEFTJOIN多个id同一个表

时间:2016-08-09 20:43:31

标签: mysql left-join

我试图从这样的表中得到一组id:

表激活:

user_id    product_id reseller_id range_id  Name
-------------------------------------------------
1              1           5          2     Oscar
1              1           5          3     Luis
2              1           5          4     Julian

表格价格(compType_id = reseller_id):

 product_id     compType_id     price   range_id 
------------------------------------------------
1                   5           38.60      2
1                   5           48.60      3
1                   5           58.60      4

表用户:

 user_id    name
----------------
    1       lloyd
    2       Mark

我想根据user_id选择激活名称和价格价格。 我怎么能这样做?

我试过这样的事情:

SELECT a.name
(SELECT price FROM prices WHERE product_id = 1 AND range_id = 
AND compType_id = 5) AS price
FROM activation AS a
LEFT JOIN users AS u ON u.user_id = a.u_id
WHERE u.user_id = 1

价格列在每行中具有相同的值。

name    price   
Oscar   21.30
Luis    21.30

如何更改它以显示正确的价格?

1 个答案:

答案 0 :(得分:0)

我用这样的东西解决了它:

SELECT a.company, a.name, a.email, a.phone, a.ruc, a.code, a.active,
a.numlic, (SELECT p.price FROM prices AS p WHERE p.product_id =
a.product_id AND p.range_id = a.range_id AND p.compType_id = c.type_id)
AS price
FROM activation AS a
LEFT JOIN users AS u ON u.user_id = a.u_id
LEFT JOIN companies AS c ON a.reseller_id = c.id
WHERE u.user_id = 1