返回在多连接情况下没有任何匹配的行

时间:2011-08-16 14:29:41

标签: mysql

我必须承认我在SQL(在这种情况下是MySQL)时非常糟糕,所以如果这很简单我会道歉!

我有以下查询:

SELECT b.tourrefcode, t.startdate, SUM(a.adults + a.children + a.infants) as Pax FROM 
explorer.booking_record b
INNER JOIN explorer.bookingroom a ON a.bookingref = b.bookingref
LEFT JOIN explorer.tour t ON b.tourrefcode = t.tourcode AND (t.startdate > '2012-02-01' AND t.startdate < '2012-03-01') AND (b.bookingstatus = "P" OR b.bookingstatus = "F") AND (b.tourdeparturedate > '2012-02-01' AND b.tourdeparturedate < '2012-03-01')
GROUP BY t.tourcode
HAVING SUM(a.adults + a.children + a.infants) < 120

这个想法是查询返回来自explorer.tour的每个游览以及在booking_record中找到的每个预订的乘客数量(在这种情况下为Pax)。 Booking_record链接到包含成人/儿童/婴儿数字的预订室。

因此,我必须在预订室加入booking_reference以获取我正在寻找的数字。

查询本身运作正常,并为我提供了正确的旅行,以便在正确的日期进行正确的旅行。但是,它不会向我展示那些没有预订的旅行。

我尝试了相同查询的许多不同构造,包括每种类型的连接,并将子句从WHERE移动到ON中(如当前实现中所示)。

任何帮助都会受到大力赞赏!

按要求说明:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  t   index       PRIMARY 11      58415   Using index; Using temporary; Using filesort
1   SIMPLE  a   ALL PRIMARY             718736  
1   SIMPLE  b   eq_ref  PRIMARY PRIMARY 5   explorer.a.bookingref   1   

问候,丹尼尔。

1 个答案:

答案 0 :(得分:0)

您正在混合左/右连接:

SELECT b.tourrefcode, t.startdate, SUM(a.adults + a.children + a.infants) as Pax FROM 
explorer.booking_record b
INNER JOIN explorer.bookingroom a ON a.bookingref = b.bookingref
RIGHT JOIN explorer.tour t ON b.tourrefcode = t.tourcode AND (t.startdate > '2012-02-01' AND t.startdate < '2012-03-01') AND (b.bookingstatus = "P" OR b.bookingstatus = "F") AND (b.tourdeparturedate > '2012-02-01' AND b.tourdeparturedate < '2012-03-01')
GROUP BY t.tourcode
HAVING SUM(a.adults + a.children + a.infants) < 120

我将一个联接更改为RIGHT JOIN。