benphp Posted February 5, 2016 Share Posted February 5, 2016 (edited) I want to fetch the titles from the Courses table, but I only want the Course Title to return once when I join Events. Courses CID | CourseTitle 1 | Course A 2 | Course B 3 | Course C Events EID | CID | EventDate 1 | 1 | 2016-02-22 2 | 1 | 2016-02-23 3 | 2 | 2016-02-24 4 | 3 | 2016-02-25 5 | 3 | 2016-02-26 If I use a JOIN, SELECT Courses.CourseTitle FROM Courses LEFT JOIN Events on (Events.CID = Courses.CID) then I get Course A Course A Course B Course C Course C But what I want is Course A Course B Course C Because ultimately, I'm going to select an Event date range, and I want to see just the courses with the event date range. Thanks! Edited February 5, 2016 by benphp Quote Link to comment Share on other sites More sharing options...
Barand Posted February 5, 2016 Share Posted February 5, 2016 SELECT DISTINCT Courses.CourseTitle ... Quote Link to comment Share on other sites More sharing options...
benphp Posted February 5, 2016 Author Share Posted February 5, 2016 OK -thanks! Yes, that works. But what if I did this: SELECT Courses.CourseTitle, Events.EventDate FROM Courses LEFT JOIN Events on (Events.CID = Courses.CID) Distinct wouldn't work, right? Quote Link to comment Share on other sites More sharing options...
Barand Posted February 5, 2016 Share Posted February 5, 2016 Correct, it won't work in that case. But that is the nature of joins. If you join one record with two matching records then the data from the one goes into both resulting records. Quote Link to comment Share on other sites More sharing options...
kicken Posted February 7, 2016 Share Posted February 7, 2016 Just because your query will pull the course name for each row doesn't mean you have to display it in the output for each row however. As you process the query results in your code you can detect when the course name has changed and only display it at that point. Alternatively you can have your code group the results by course then output the results with some nested loops. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.