【发布时间】:2016-09-11 01:30:47
【问题描述】:
我有一个大的多表查询连接选择,其中一些值是可选的。
这是查询:
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 的表和以下列(id、services_id、reservation_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
有什么想法吗?
【问题讨论】:
-
简单规则:从不在
FROM子句中使用逗号。 始终在ON子句中的条件下使用显式JOIN语法。 -
@Gordon Linoff - 这能解决我的问题吗?
-
正如@GordonLinoff 已经说过的,使用明确的
JOIN语法,这将允许您指定组合的行为(LEFT,INNER ...)。您很可能会在适当的情况下使用侧连接来实现您的结果。 -
@Lachesis 。 . .不是直接的。但它会让你的查询更容易理解,从而让其他人更容易帮助你。