简体   繁体   中英

MySQL How to Get Query To Display Seminars With No Customers Attending

I am new to SQL and trying to write a query in MySQL for a database I have created. The query is meant to display each seminar that is hosted and the information of each customer attending it. The query is also meant to display the seminars which nobody attends. How would I get it to do this? Thank you for any help ahead of time.

SELECT sem.SeminarID, sem.SeminarDate, sem.Location, sem.SeminarTitle, cust.CustomerID, cust.LastName, cust.FirstName
FROM seminar AS sem JOIN 
     seminar_customer as SC on sem.SeminarID = SC.SeminarID JOIN
     customer AS cust on SC.CustomerID = cust.CustomerID        
ORDER BY SeminarID;

You require an "OUTER JOIN" which allows some rows of your seminar table to be returned that have no matching row in the seminar_customer table.

In the way your query is laid out seminar_customer is on the "left", so use a "LEFT OUTER JOIN"

SELECT sem.SeminarID, sem.SeminarDate, sem.Location, sem.SeminarTitle, cust.CustomerID, cust.LastName, cust.FirstName
FROM seminar AS sem   seminar_customer as SC on sem.SeminarID = SC.SeminarID 
                      customer AS cust on SC.CustomerID = cust.CustomerID        
ORDER BY SeminarID;

See: A Visual Explanation of SQL Joins

You can omit the word "OUTER" in those joins, so often you will just see "LEFT JOIN" instead, but they are the same things

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