我想从三个表中提取数据,但如果第三个表中不存在数据,则应拉出其他两个表中的数据。
我现在有一个查询:
SELECT m.name, m.zipcode, p.lat, p.lon, meta.meta_value
FROM members AS m
INNER JOIN zipcodes AS p ON m.zipcode = p.zipcode
INNER JOIN usermeta AS meta ON m.id = meta.id
WHERE m.zipcode = p.zipcode AND meta.meta_key = 'image' m.country = "USA"
所有人都不存在 m.id
和meta.id
。
对于那些m.id
的人,“图像”并不存在。
我想从其他2个表中提取数据,与“image”和m.id
的存在无关。
我该怎么做?
答案 0 :(得分:1)
您正在使用INNER JOIN;使用OUTER JOINS从条件为false的连接表中的列中获取NULL值。
例如:
SELECT m.name, m.zipcode, p.lat, p.lon, meta.meta_value
FROM members AS m
LEFT OUTER JOIN zipcodes AS p ON m.zipcode = p.zipcode
LEFT OUTER JOIN usermeta AS meta ON m.id = meta.id
WHERE m.zipcode = p.zipcode AND meta.meta_key = 'image' m.country = "USA"
答案 1 :(得分:0)
如何将查询更改为
SELECT m.name, m.zipcode, p.lat, p.lon, meta.meta_value
FROM members AS m
INNER JOIN zipcodes AS p ON m.zipcode = p.zipcode
LEFT OUTER JOIN usermeta AS meta ON m.id = meta.id
WHERE m.zipcode = p.zipcode AND COALESCE(meta.meta_key,'image')='image' AND m.country = 'USA'