Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdrstrangequark
8,273 PointsStill having issues with Joins
In SQL Playgrounds for Beginner SQL -> Querying Relational Databases -> Subqueries -> Review and Practice, the second assignment is:
-- Generate a report that lists a patron's first name, email and loan count for loans that haven't been returned.
This time, I'm unsure what I'm doing wrong. It tells me there is a syntax error near "INNER" but I'm still pretty lost. My query is:
SELECT patrons.first_name, patrons.last_name, patrons.email, COUNT(*) FROM ( SELECT * FROM loans_north UNION ALL SELECT * FROM loans_south ) AS total_loans WHERE returned_on IS NULL INNER JOIN patrons ON patrons.id = total_loans.id GROUP BY patron_id;
1 Answer
Steven Parker
231,184 PointsYou were pretty close the first time, and had a good idea about having the WHERE
outside of the subquery but it needed to come after the JOIN
:
-- Generate a report that lists a patron's first name, email and loan count
-- for loans that haven't been returned.
SELECT first_name, email, COUNT(1) AS "loan count"
FROM (SELECT * FROM loans_north UNION ALL SELECT * FROM loans_south) AS total_loans
INNER JOIN patrons ON patrons.id = total_loans.patron_id
WHERE returned_on IS NULL
GROUP BY patron_id;
drstrangequark
8,273 Pointsdrstrangequark
8,273 PointsNEVERMIND! I think I got it:
SELECT p.id AS "Patron ID", p.first_name AS "First Name", p.last_name AS "Last Name", p.email AS "Email", COUNT(*) AS "Unreturned Loan Count" FROM
( SELECT * FROM loans_north WHERE returned_on IS NULL
UNION ALL
SELECT * FROM loans_south WHERE returned_on IS NULL) AS total_loans
INNER JOIN patrons AS p ON p.id = total_loans.patron_id
GROUP BY p.id;
I'm sure that it can be cleaned up a bit but it got me the info I needed!