[英]MySQL Query using data from two tables
I have two tables like so: 我有两个这样的表:
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
I need to show only ONE "track" from table 1 for each festival listing from Table 2 like so: Results: 对于表2中的每个节日列表,我只需要显示表1中的一个“曲目”,如下所示:结果:
Copperland Festival:
-----------------------
Tom Smith This Time is Right Time
John Doe Every Time I See You
In layman's terms, the logic would be along the lines of: Get only one track from TABLE 1 where artist equals (or matches) fest_artist from TABLE 2 用外行的话来说,逻辑将遵循以下原则:从表1中仅获得一条曲目,其中艺术家与表2中的fest_artist相等(或匹配)
I referenced a similar question which advised something in the direction of: $sql="select * from tracks WHERE (artist) in (select fest_artist from festival_bands group by name)"
but with no luck. 我引用了一个类似的问题,该问题向以下方向提出了建议:
$sql="select * from tracks WHERE (artist) in (select fest_artist from festival_bands group by name)"
但是没有运气。
You can use a correlated subquery to get a random track for the artist: 您可以使用相关子查询来获取艺术家的随机曲目:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.