简体   繁体   中英

How to get already booked customers in MySQL query?

I have this SQL Fiddle: 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)
;

My Query below:

SELECT m.memberName, e.id, e.enq_status 
FROM enquiry e,members m 
WHERE e.memberId = m.id AND e.enq_status = '';

In which I have members , enquiry and bookings table. In my query shown in SQLFiddle, I am retrieving the enquiries which are not cancelled or booked.

But I want to highlight or maybe add a column which will tell us that the customer who made the enquiry have already booked previously or not.

What could be the solution for it based on the above Fiddle, please advise!

You have to use some tables more than once, and also you have to use LEFT JOIN for conditionally join the previous possible bookings.

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;
  • Start with enquiries that are pending ( enq_status='' )
  • Get member data for that (that always exists, so use simple JOIN )
  • Get possible enquiries for the members (POSSIBLE -> LEFT JOIN )
  • Get possible bookings for those possible enquiries ( LEFT JOIN again)
  • Then, count the number of bookings found, for each (original) enquiry ( GROUP BY )
  • Also, order by the count

I think this is what you want. Instead of counting ( COUNT(b.id) ), you can use any other metrics, eg SUM(b.amount) for using the total amount as ordering factor, or COUNT(b.id)*10 + SUM(b.amount) which is a combination of order count and total amount, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM