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 trial

Databases

Querying relational databases Subqueries

I am kind of stuck on the querying relational databases course by Andrew Chalkey..

I have produced the following for on of the questions but not sure if its correct or wether there is a better way, I am sure there is lol:

Here is my attempt:

   -- 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, id, COUNT(id) AS "Loan Count" FROM patrons AS p
  INNER JOIN (SELECT loans_south.patron_id FROM loans_south WHERE returned_on IS NULL) AS t
  ON t.patron_id = p.id
  GROUP BY t.patron_id
    UNION
  SELECT first_name, email, id, COUNT(id) AS "Loan Count" FROM patrons AS pat
  INNER JOIN (SELECT loans_north.patron_id FROM loans_north WHERE returned_on IS NULL) AS tem
  ON tem.patron_id = pat.id
  GROUP BY tem.patron_id
  ORDER BY "Loan Count" DESC;

The second query after the union is just a copy of the one above but searching through the second table called loans_north I wish i could just get it to look through the one joined table..

I also wonder if in a sub query where you put the query in brackets if you can do something

like (SELECT name from table_one UNION SELECT name from table_two) this would hopefully union two tables and this could be the derived table...

Can you store results from queries in variables.. and then pass them to other queries ?

1 Answer

I am to long out of the topic to answer this question directly

Thanks