Mysql 即使条目不存在也返回值
我正在使用以下查询:Mysql 即使条目不存在也返回值,mysql,Mysql,我正在使用以下查询: 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_图像中的行没有链接。因
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_图像中的行没有链接。因此其中shop\u entrys.id=shop\u images.s\u id。。。不会得到满足。在这种情况下,我仍然希望返回一个结果。例如:
shop\u entrys.id shop\u images.path
1“/img1.jpg”
... ...
42“未找到”
如何更改上述查询以仍返回结果?使用
左连接和合并()
请避免使用隐式连接语法(逗号分隔),因为它已被弃用,而且很混乱,而且很多时候会导致错误。仅使用连接的正确语法 使用带COALESCE的左外部联接为第二列提供默认值
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
使用左外联接?谢谢,你能告诉我为什么不应该使用隐式联接语法吗?这是我在学校学到的方法。好吧,当加入多个表格时,原因更加明显和清楚。尝试理解一个查询,该查询使用隐式联接语法联接7个表,这是永远不会发生的。。另一个原因是带有隐式联接语法的左联接
,这使得它更加复杂,并造成限制(一个表只能外部联接到一个表等)@Bobface@Bobface-当人们混合使用隐式联接和显式联接时,可能会导致问题的另一个问题是它们具有不同的优先级。
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