当可选的FK行不存在于PK行(1到none / many)时,正确的sql查询返回null

时间:2014-08-09 08:36:00

标签: mysql sql outer-join table-alias

为mysql编写此查询的正确方法是什么(这似乎有用,但似乎很愚蠢)(191是变量的硬编码)

select t1.item_id, t1.item_name, t1.item_desc, t.quantity, t.price 
from (select * from items i where i.item_id = 191) as T1
LEFT JOIN (select * from item_properties ip) as T
on t1.item_id = t.fk_item_id and t1.item_id=191;

T1.item_id是PK,T.fk_item_id是外键(? - 只有父T1.item_id存在才能存在)

这是我将t.values作为null的方式,当它们不存在时(并且无法加入)。

由于

2 个答案:

答案 0 :(得分:0)

如果你想阅读如何在mysql read this

中正确实现连接

如果你想要结果只有两个表中的匹配使用FK和PK的内部连接

答案 1 :(得分:0)

SELECT
    i.item_id, i.item_name, i.idem_desc,
    p.quantity, p.price
FROM items i
LEFT JOIN item_properties p ON i.item_id = p.fk_item_id
WHERE i.item_id = 191

左连接是必需的,因此即使右表中没有匹配的行,也始终返回左表中的行。但是FROM中的SELECT不是必需的。尽量保持简单。