簡體   English   中英

帶有GROUP_CONCAT的INNER JOIN返回重復值

[英]INNER JOIN with GROUP_CONCAT returns repeating values

如果嘗試使用以下查詢來查詢數據庫,則會得到預期的結果:

SELECT anime.anime, GROUP_CONCAT(themes.theme) AS themes
FROM anime
INNER JOIN anime_themes ON anime.id = anime_themes.anime_id
INNER JOIN themes ON themes.id = anime_themes.theme_id
GROUP BY anime.anime
ORDER BY anime.id;

示例輸出: “健忘症,身體切換,自然災害,悲劇”

但是,當我嘗試使用以下查詢一次查詢更多數據時,會得到重復數據:

SELECT anime.*, directors.director, studios.studio, 
GROUP_CONCAT(genres.genre) AS genres, GROUP_CONCAT(themes.theme) AS themes
FROM anime
INNER JOIN anime_directors ON anime.id = anime_directors.anime_id
INNER JOIN directors ON directors.id = anime_directors.director_id
INNER JOIN anime_studios ON anime.id = anime_studios.anime_id
INNER JOIN studios ON studios.id = anime_studios.studio_id
INNER JOIN anime_genres ON anime.id = anime_genres.anime_id
INNER JOIN genres ON genres.id = anime_genres.genre_id
INNER JOIN anime_themes ON anime.id = anime_themes.anime_id
INNER JOIN themes ON themes.id = anime_themes.theme_id
GROUP BY anime.anime
ORDER BY anime.id;

示例輸出: bodyswitch,自然災害,悲劇,健忘症,失憶,bodydisaster,自然災害,自然災害,悲劇,失憶,健忘症,bodyswitch,自然災害,悲劇,悲劇,失憶,bodyswitch”

在第二個查詢中,數據似乎並沒有以連貫的順序重復。 為什么兩個查詢之間的行為不同,我該如何解決呢? 謝謝。

編輯:只有“主題”和“類型”具有重復的值,而“導演”和“工作室”則沒有,因此我認為它與GROUP_CONCAT函數有關。

只需添加DISTINCT。

例:

    GROUP_CONCAT(DISTINCT genres.genre) AS genres, GROUP_CONCAT(DISTINCT 
 themes.theme) AS themes

您在第二個查詢中加入更多表,這可能導致一條記錄重復出現。 添加“ DISTINCT”可能會刪除重復的值,但這不是優化此查詢的最佳方法。 您還應該考慮使用子查詢或左聯接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM