简体   繁体   English

MySQL-根据条件联接3个表

[英]MySQL - join 3 tables based on criteria

Please help a MySQL newbie. 请帮助MySQL新手。 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. 我有3个表:表users-用户名是主键,表歌曲-idsong是主键,第二列是标题,购买的第三张表以“ ref”列作为主键,“ idsong”是歌曲表中的外键和“ username” ”是来自用户表的外键。 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. 这为我提供了用户的歌曲ID,但是我不确定如何添加标题以从第三张表中显示。 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';   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM