我有3张桌子。 items
,shops
和支点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
答案 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