MySQL - 检查一行中的多个相同值

时间:2013-12-31 09:38:06

标签: php mysql

我有一个MySQL表格,其中包含图表列表中歌曲的以下结构。

ID - Title - Artist - Releaseyear - 1999 - 2000 - 2001 - 2002 - 2003 - ..etc .. - - 2013.

专栏' 1999',' 2000'等等是当年图表中歌曲的位置。

现在我想在至少三年内检查哪些歌曲在同一个地方。

我找到了在多行上查找重复项的查询,但在这种情况下还没有。

1 个答案:

答案 0 :(得分:3)

使用UNION将列转换为行,然后您可以找到重复的行。

SELECT ID, place, GROUP_CONCAT(year ORDER BY year) years
FROM ( -- Pivot the table to get all the years and places in the same column
    SELECT ID, "2001" AS year, `2001` AS place
    UNION
    SELECT ID, "2002" AS year, `2001` AS place
    UNION
    ...
    UNION
    SELECT ID, "2013" AS year, `2013` AS place
    ) AS byYear
GROUP BY ID, place
HAVING COUNT(*) >= 3