我有两张桌子,a和b
表a
--------------------
|id | item |
--------------------
|1 | apple |
--------------------
|2 | orange |
--------------------
|3 | mango |
--------------------
|4 | grapes |
--------------------
|5 | plum |
--------------------
|6 | papaya |
--------------------
|7 | banana |
--------------------
表b
----------------------------
user_id | item_id | price |
----------------------------
32 | 3 | 250 |
----------------------------
32 | 6 | 180 |
----------------------------
32 | 2 | 120 |
----------------------------
现在我想加入MySql中的两个表,以便获得表a中所有水果的列表以及用户32的表b中的价格;像这样的东西:
-----------------------------
|id | item | price |
-----------------------------
|1 | apple | |
-----------------------------
|2 | orange | 120 |
------------------------------
|3 | mango | 250 |
------------------------------
|4 | grapes | |
------------------------------
|5 | plum | |
------------------------------
|6 | papaya | 180 |
------------------------------
|7 | banana | |
------------------------------
我能做的最好的就是:
SELECT a.id,
a.item,
b.price
FROM a
INNER JOIN b ON a.id = b.item_id
WHERE b.user_id = 32
这只给出了价格已设定的行,而不是价格尚未设定的行。如何构建SQL?
答案 0 :(得分:4)
使用LEFT OUTER JOIN代替 INNER JOIN
试试这个:
SELECT a.id, a.item, b.price
FROM a
LEFT OUTER JOIN b ON a.id = b.item_id AND b.user_id = 32;
答案 1 :(得分:1)
您必须使用OUTER JOIN
SELECT a.id, a.item, b.price
FROM a LEFT OUTER JOIN b ON a.id = b.item_id WHERE b.user_id = 32
答案 2 :(得分:-1)
您需要“LEFT”加入以确保无论右侧的相应值如何,都会返回左侧的所有记录。
SELECT a.id, a.item, b.price
FROM a
LEFT JOIN b ON a.id = b.item_id
WHERE b.user_id = 32