仅从3表加入

时间:2018-02-20 02:12:39

标签: mysql join duplicates many-to-many

我有一张这样的表

comptitle,trknum,cdtitle "A-Tisket, A-Tasket",4,Swing Choo Choo Ch' Boogie,13,Swing Clouds,10,Swing Countdown,11,Giant Steps Countdown,3,Giant Steps Cousin Mary,10,Giant Steps Cousin Mary,14,Swing Cousin Mary,2,Giant Steps Down South Camp Meetin',8,Swing Giant Steps,1,Giant Steps Giant Steps,8,Giant Steps I Know Why,5,Swing It's a Good Enough to Keep,12,Swing Java Jive,7,Swing Mr. P.C.,7,Giant Steps Naima,6,Giant Steps Naima,9,Giant Steps Sing a Study in Brown,2,Swing Sing Moten's Swing,3,Swing Sing You Sinners,6,Swing Skyliner,11,Swing Spiral,4,Giant Steps Stomp of King Porter,1,Swing Syeeda's Song Flute,12,Giant Steps Syeeda's Song Flute,5,Giant Steps Topsy,9,Swing

我从这个查询得到的

SELECT comptitle, trknum, cdtitle from composition join track on track.compid = composition.compid join cd on cd.cdid = track.cdid group by comptitle, trknum, cdtitle order by comptitle, trknum;

我只想显示comptitle(第一列)是重复的行,所以结果应该是这个

comptitle,trknum,cdtitle Countdown,11,Giant Steps Countdown,3,Giant Steps Cousin Mary,10,Giant Steps Cousin Mary,14,Swing Cousin Mary,2,Giant Steps Giant Steps,1,Giant Steps Giant Steps,8,Giant Steps Naima,6,Giant Steps Naima,9,Giant Steps Syeeda's Song Flute,12,Giant Steps Syeeda's Song Flute,5,Giant Steps

我尝试过使用count,但having count(comptitle) > 1会返回每一行,而不仅仅是那些有重复的行。

1 个答案:

答案 0 :(得分:0)

如果没有记错,表track会存储每个构图的曲目数。在这种情况下,您可以创建一个子查询,使compid具有多个轨道

SELECT 
    comptitle, trknum, cdtitle 
FROM
    composition
JOIN
    track ON track.compid = composition.compid
JOIN 
    cd ON cd.cdid = track.cdid
INNER JOIN
    (SELECT compid
     FROM track
     GROUP BY compid
     HAVING COUNT(compid) > 1) cc ON composition.compid = cc.compid
GROUP BY
    comptitle, trknum, cdtitle
ORDER BY 
    comptitle, trknum;

在我看来,如果你能给我们每个表和样本记录的关系,这个查询仍然可以简化。