我有这个SQL小提琴:http://sqlfiddle.com/#!9/abe27/2
CREATE TABLE members
(`id` int, `memberName` varchar(7))
;
INSERT INTO members
(`id`, `memberName`)
VALUES
(1, 'Steve'),
(2, 'John'),
(3, 'Alex')
;
CREATE TABLE enquiry
(`id` int, `memberId` int, `enq_status` varchar(20))
;
INSERT INTO enquiry
(`id`, `memberId`, `enq_status`)
VALUES
(1, 1, 'Cancelled'),
(2, 1, 'Booked'),
(3, 3, 'Booked'),
(4, 2, 'Cancelled'),
(5, 3, 'Booked'),
(6, 3, ''),
(7, 2, ''),
(8, 1, '')
;
CREATE TABLE bookings
(`id` int, `enquiryId` int)
;
INSERT INTO bookings
(`id`, `enquiryId`)
VALUES
(1, 2),
(2, 3),
(3, 5)
;
我的查询如下:
SELECT m.memberName, e.id, e.enq_status
FROM enquiry e,members m
WHERE e.memberId = m.id AND e.enq_status = '';
我有members
,enquiry
和bookings
表格。在SQLFiddle中显示的查询中,我正在检索未取消或已预订的查询。
但我想强调或者添加一个专栏,告诉我们进行查询的客户之前已经预订过。
基于上面的小提琴可能有什么解决方案,请指教!
答案 0 :(得分:2)
您必须多次使用某些表格,并且还必须使用LEFT JOIN
有条件地加入之前的预订。
SELECT e.id, m.memberName, e.enq_status, COUNT(b.id) as booking_count
FROM enquiry e
JOIN members m ON (e.memberId = m.id)
LEFT JOIN enquiry e2 ON (e2.memberId = m.id)
LEFT JOIN bookings b on (b.enquiryId=e2.id)
WHERE e.enq_status = ''
GROUP BY e.id
order by booking_count desc;
enq_status=''
)JOIN
)LEFT JOIN
)LEFT JOIN
再次)GROUP BY
)我认为这就是你想要的。
您可以使用任何其他指标(例如COUNT(b.id)
)将总金额用作排序因子,或SUM(b.amount)
这是订单计数和总金额的组合,而不是计算(COUNT(b.id)*10 + SUM(b.amount)
),等