简体   繁体   中英

MySQL - join 3 tables based on criteria

Please help a MySQL newbie. I have 3 tables: table users-username is primary key, table song - idsong is primary key and second column is title, third table purchased with column "ref" as primary key, "idsong" is foreign key from song table and "username" is foreign key from users table. So I need to generate a query that will pull which songs has a particular user purchased, and I need the titles display. So far I have:

SELECT idsong FROM purchased  
   JOIN users ON users.username=purchased.username  
   WHERE users.username='admin';   

and this gives me the song id for the user, but I am not sure how to add the title to display from the third table. Please help!

SELECT s.idsong, s.title
  FROM purchased p 
 INNER JOIN users u ON u.username=p.username
 INNER JOIN song s ON p.idsong = s.idsong
 WHERE u.username='admin';   

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