MySQL Query使用来自两个表的数据

时间:2018-06-03 14:52:51

标签: mysql sql

我有两张桌子:

Table 1: tracks
id  | artist     | track
---------------------------------------
1     Tom Smith    This Time is Right Time
2     Tom Smith    Oh Yes
3     John Doe     Every Time I See You

Table 2: festival_bands
id  | fest_title | fest_artist
---------------------------------------
1     Hoe Down Fest 2019    John Doe
2     Copperland Fest       Tom Smith
3     Copperland Fest       Reggie Wisk
4     Copperland Fest       Tom Smith
5     Copperland Fest       John Doe
6     Bluegrass Memories    John Doe

对于表2中的每个节日列表,我需要从表1中仅显示一个“曲目”,如下所示: 结果:

Copperland Festival:
-----------------------
Tom Smith    This Time is Right Time
John Doe     Every Time I See You

用外行人的话说,逻辑将是: 从表1中只获取一个曲目,其中艺术家等于(或匹配)来自表2的fest_artist

我提到了一个类似的问题,它提出了以下方面的建议: $sql="select * from tracks WHERE (artist) in (select fest_artist from festival_bands group by name)"但没有运气。

1 个答案:

答案 0 :(得分:0)

您可以使用相关子查询为艺术家获取随机曲目:

select fb.*,
       (select t.track
        from tracks t
        where t.artist = fb.fest_artist
        order by t.counter desc
       ) as most_popular_track
from festival_bands fb;