MYSQL查询生成JOIN的一个重复行

时间:2012-01-26 23:08:45

标签: mysql database database-design join

编辑:非常感谢谢尔盖为我解决这个问题。一旦他得到它作为答案,我会标记并回答。

我的查询如下所示:

 SELECT SQL_CALC_FOUND_ROWS
    songsID, song_name, artist_band_name, author, song_artwork, song_file,
    genre, song_description, uploaded_time, emotion, tempo,
    user, happiness, instruments, similar_artists, play_count,
    projects_count,
    rating, ratings_count, waveform, datasize, display_name, user_url, genre_id, 
    IF(user_ratings_count, 'User Voted', 'Not Voted') as voted 
FROM (
        SELECT  
            sp.songsID, projects_count, 
            AVG(rating) as rating,
            COUNT(rating) AS ratings_count,
            COUNT(IF(userid=$userid, 1, NULL)) as user_ratings_count

                FROM (
                    SELECT songsID, COUNT(*) as projects_count
                    FROM $sTable s
                    LEFT JOIN $sTable2 p ON s.songsID = p.songs_id

                    GROUP BY songsID) as sp

            LEFT JOIN $sTable3 r ON sp.songsID = r.songid           

            GROUP BY sp.songsID) as spr

LEFT JOIN $sTable6 gs ON gs.song_id = songsID  

JOIN $sTable s USING (songsID)
LEFT JOIN $sTable5 q ON s.user = q.ID   

虽然这个查询返回了各个表中的所有信息(所有表都指定为$ sTable,$ sTable2,$ sTable3等),但是它给了我基于$ sTable6的重复行。

这只发生在$ sTable6 JOIN到位的情况下,从底部开始的第三行:

LEFT JOIN $sTable6 gs ON gs.song_id = songsID  

删除此行后一切正常。但是,我需要检索此信息,以便通过'genre_id'提供动态过滤。目前它从$ sTable中检索所有行以及来自其他各种表的所有相应信息,但也重新打印$ sTable中与$ sTable6共享song_id / songsID的任何行。

我该如何防止这种情况?

1 个答案:

答案 0 :(得分:0)

您在LEFT JOINed表中有重复的song_id。我使用类似下面的内容将JOIN限制为只有一个匹配的记录:

编辑:

LEFT JOIN $sTable6 gs ON gs.song_id = songsID AND gs.MYUNIQUECOLUMN IN (SELECT MYUNIQUECOLUMN FROM $sTable6 WHERE song_id = songsID ORDER BY MYUNIQUECOLUMN LIMIT 1)