我使用以下查询:
SELECT shop_entrys.id, shop_images.path FROM shop_entrys,shop_images
WHERE shop_entrys.id = shop_images.s_id AND
shop_images.pos = 0 AND
shop_entrys.category_id = 1
ORDER BY shop_entrys.pos ASC
但是, shop_entrys 中的一行可能存在,并且没有链接到 shop_images 中的行。因此, ... WHERE shop_entrys.id = shop_images.s_id ... 将无法满足。在这种情况下,我仍然想要返回一个结果。例如:
shop_entrys.id shop_images.path
1 "/img1.jpg"
... ...
42 "not found"
如何更改上述查询仍然返回结果?
答案 0 :(得分:4)
使用LEFT OUTER JOIN和COALESCE为第2列提供默认值
SELECT shop_entrys.id, COALESCE(shop_images.path, 'NOT FOUND' )
FROM shop_entrys
LEFT OUTER JOIN shop_images
ON shop_entrys.id = shop_images.s_id AND shop_images.pos = 0
WHERE shop_entrys.category_id = 1
ORDER BY shop_entrys.pos ASC
答案 1 :(得分:3)
使用LEFT JOIN
和COALESCE()
:
SELECT shop_entrys.id,
COALESCE(shop_images.path,'NOT FOUND')
FROM shop_entrys
LEFT JOIN shop_images
ON(shop_entrys.id = shop_images.s_id AND
shop_images.pos = 0)
WHERE shop_entrys.category_id = 1
ORDER BY shop_entrys.pos
请避免使用隐式连接语法(以逗号分隔),因为它已被弃用且混乱,并且很多时候都会导致错误。仅使用 正确的连接语法!