获得所有商店,如果附加了特定商品,则附上“附件”

时间:2014-05-12 14:11:57

标签: sql

我有3张桌子。 itemsshops和支点shop_item

我想检索所有商店,但如果给定商品附加到商店,则需要额外字段attached

以下内容有效,但并未指定要设置Attached参数的项目。

我在某个地方成像WHERE shop_item.item_id = 1,但我还没有设法让它发挥作用。

如何实现参数?

SELECT shops.*, shop_item.id AS attached FROM shops
LEFT OUTER JOIN shop_item
ON shops.id = shop_item.shop_id

2 个答案:

答案 0 :(得分:2)

您希望将此条件放在on子句中,而不是where子句中:

SELECT shops.*, shop_item.id AS attached
FROM shops LEFT OUTER JOIN
     shop_item
     ON shops.id = shop_item.shop_id and shopt_item.item_id = 1;

如果你把它放在where条款中,它将"撤消" LEFT OUTER JOIN,将其变为INNER JOIN

答案 1 :(得分:0)

如果您只想要附加项目,请使用INNER JOIN

SELECT shops.*, shop_item.id AS attached
FROM shops
    INNER JOIN shop_item ON shops.id = shop_item.shop_id

如果您想要attached的布尔值,那么您需要评估该值,但将其保留为LEFT OUTER JOIN

SELECT shops.*,
    CASE WHEN shop_item.id IS NULL THEN 0 ELSE 1 END CASE AS attached
FROM shops
    LEFT OUTER JOIN shop_item ON shops.id = shop_item.shop_id