合并并显示查询结果

时间:2019-11-29 07:20:33

标签: mysql sql

我有2个查询:

SELECT CustomerID,count(b.BookingStatus) as 'NotComplete'
FROM Booking b, Customer c 
WHERE c.CustomerID=b.BookingCustomerID
AND(b.BookingStatus='Pending'
OR b.BookingStatus='OTW')
GROUP BY c.CustomerID


SELECT c.CustomerID, r.*
FROM Customer c,Regular r
WHERE c.CustomerID=r.RegularCID
Result:

第一个查询enter image description here

第二次查询enter image description here

如何将这两个结果结合在一起?

还要显示零(计数)。

谢谢!


这是我经过几个小时的尝试而得到的。显然,这不是我想要的。

SELECT c.CustomerID,count(b.BookingStatus) as 'NotComplete',r.RegularID
FROM Booking b, Customer c 
JOIN Regular r on r.RegularCID=c.CustomerID
WHERE c.CustomerID=b.BookingCustomerID

AND (b.BookingStatus='Pending'
or b.BookingStatus='OTW'
or b.BookingStatus='Started'
or b.BookingStatus='Unclaimed'
or b.BookingStatus='Confirmed')
GROUP by r.RegularID   

2 个答案:

答案 0 :(得分:1)

您可以JOINRegular表,然后LEFT JOINBooking表中的派生计数表。我们这样做是为了避免必须GROUP BY表中的所有列Regular

SELECT c.CustomerID, r.*, b.NotComplete
FROM Customer c
JOIN Regular r ON r.RegularCID = c.CustomerID
LEFT JOIN (SELECT BookingCustomerID, COUNT(*) AS NotComplete
           FROM Booking
           WHERE BookingStatus IN ('Pending', 'OTW', 'Started', 'Unclaimed', 'Confirmed')
           GROUP BY BookingCustomerID) b ON b.BookingCustomerID = c.CustomerID

答案 1 :(得分:0)

regular表上使用联接,并在第一个subquery上使用select

SELECT t1.*, r.RegularCID FROM (
    SELECT CustomerID,count(b.BookingStatus) as 'NotComplete',
    FROM Booking b
    INNER JOIN Customer c ON c.CustomerID=b.BookingCustomerID
    WHERE (b.BookingStatus='Pending' OR b.BookingStatus='OTW')
    GROUP BY c.CustomerID) t1
LEFT JOIN Regular r on r.CustomerID = t1.CustomerID