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 trialAbhinav Kanoria
7,730 PointsA problem on writing SQL query
Consider the following library database: member(memb_no, name, age) with primary key as memb_no.
book(isbn, title, author, publisher) with primary key as isbn.
borrowed(memb_no, isbn, date) with primary key as memb_no, isbn.
Write SQL queries for the following: A) Print the names of all members who have borrowed any book published by 'Mc Graw Hill'. B) For each publisher, print the names of members who have borrowed more than five books of that publisher.
I don't know how to write the SQL for part A. For part B this is what I wrote:
SELECT publisher, name FROM member, book, borrowed WHERE member.memb_no = borrowed.memb_no AND book.isbn = borrowed.isbn GROUP BY publisher, name HAVING COUNT(isbn) > 5;
Is the above query for part B formulated correctly? And how do I write query for part A? Please help. If you want to know anything else about this question, please let me know. Thanks!!
1 Answer
Gabor Gazdag
10,474 PointsDear Abhinav,
Hereby my suggestion for the question A. I do prefer using aliases instead of joins:
SELECT a.name
FROM member a, book b, borrowed c WHERE a.memb_no=c.memb_no AND b.isbn=c.isbn AND b.publisher="Mc Graw Hill"
The solution for question B would be: SELECT publisher FROM (SELECT b.publisher publisher, count(c.isbn) FROM member a, book b, borrowed c WHERE a.memb_no=c.memb_no AND b.isbn=c.isbn GROUP BY publisher HAVING COUNT(c.isbn) > 5)
Cheers, Gabor