SQL:连接选择缺少行的多个表

时间:2016-09-10 17:12:51

标签: mysql sql

我有一个很大的多表查询连接选择,其中某些值是可选的。

这是查询:

SELECT a.date_in, a.date_out, b.name, b.phone, b.birthdate,
b.country, b.hotel, b.room_nr, b.passport_nr, c.email,
d.size, e.name, GROUP_CONCAT(DISTINCT g.service), GROUP_CONCAT(DISTINCT     h.service)
, GROUP_CONCAT(DISTINCT i.time), GROUP_CONCAT(DISTINCT j.location)
FROM reservation a, rider b, user c,
bike_size d, bike e, services_reservation f, services g,
bike_shipping h, bike_shipping_reservation i
, bike_shipping_location j WHERE a.rider_id = b.id
AND b.user_id = c.id AND a.bike_size_id = d.id AND
d.bike_id = e.id AND a.id = f.reservation_id AND
f.services_id = g.id
AND h.id = i.bike_shipping_id AND a.id = i.reservation_id
AND i.bike_shipping_location_id = j.id
AND a.id = 80 

在上面查询的表格中,名为services_reservation的表格包含以下列(idservices_idreservation_id)在这种情况下完全为空,使我从表bike_shipping_reservation中选择的值为NULL。

我如何制作一些我从可选项中选择的表,以防它们为空?

这里是带有1个空表的SQL Fiddle,你可以在结尾看到NULL结果(只有GROUP_CONCAT(DISTINCT g.service)应为NULL)。

http://sqlfiddle.com/#!9/ee31b/6

这里是SQL Fiddle,其中所有表都有列中的值,您可以看到返回的所有值都不是NULL。

http://sqlfiddle.com/#!9/8bc033/34

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

在不匹配

的情况下使用表格(或行)为空的左连接
SELECT a.date_in, a.date_out, b.name, b.phone, b.birthdate,
b.country, b.hotel, b.room_nr, b.passport_nr, c.email,
d.size, e.name, GROUP_CONCAT(DISTINCT g.service), GROUP_CONCAT(DISTINCT     h.service)
, GROUP_CONCAT(DISTINCT i.time), GROUP_CONCAT(DISTINCT j.location)

FROM reservation a 
INNER JOIN rider b on  a.rider_id = b.id 
INNER JOIN user c on b.user_id = c.id  
INNER JOIN bike_size d on a.bike_size_id = d.id 
INNER JOIN bike e ON d.bike_id = e.id  
LEFT  JOIN services_reservation f on  a.id = f.reservation_id   
INNER JOIN services g on f.services_id = g.id
INNER JOIN bike_shipping_reservation i on a.id = i.reservation_id
INNER JOIN bike_shipping h ON h.id = i.bike_shipping_id
INNER JOIN bike_shipping_location j on i.bike_shipping_location_id = j.id
where a.id = 80