MySQL - 获取列的所有唯一值,检查是否具有特定值

时间:2010-03-22 06:26:50

标签: mysql

首先 - 为糟糕的头衔道歉,我不知道如何用单行描述它。 我有一张桌子 - 下面是片段。

mysql> select * from playlistfiles;
+-----------------------+--------------+-----------+
| FileName              | PlaylistName | FileIndex |
+-----------------------+--------------+-----------+
| File1                 | Image1       |         0 | 
| File1                 | Video1       |         2 | 
| File2                 | Video1       |         0 | 
| File3                 | Video1       |         1 | 
| File4                 | Image1       |         1 | 
| File4                 | Video1       |         3 | 
+-----------------------+--------------+-----------+
6 rows in set (0.00 sec)

我需要做的是获取所有FileNames以及文件是否在播放列表中,以及通过FileIndex对它们进行排序,即对于Image1播放列表,输出应为

+-----------------------+------------+-----------+
| FileName              | InPlaylist | FileIndex |
+-----------------------+------------+-----------+
| File1                 |          1 |         0 | 
| File2                 |          0 |      Null | 
| File3                 |          0 |      Null | 
| File4                 |          1 |         1 | 
+-----------------------+------------+-----------+

和Video1将是

+-----------------------+------------+-----------+
| FileName              | InPlaylist | FileIndex |
+-----------------------+------------+-----------+
| File2                 |          1 |         0 | 
| File3                 |          1 |         1 | 
| File1                 |          1 |         2 | 
| File4                 |          1 |         3 | 
+-----------------------+------------+-----------+

简而言之,我需要能够从表中获取所有唯一的FileNames,并检查它是否在给定的表中,如果是,请通过FileIndex对其进行排序。

1 个答案:

答案 0 :(得分:0)

我会从这样开始并从那里开始玩:

select plf.fileName,
max(if(plf2.fileName = plf.fileName, 1, 0)) as inPlayList,
max(plf2.FileIndex)

from playlistfiles plf

left join playlistfiles plf2
on plf.fileName = plf2.fileName
and plf2.playListName = @playListName

group by plf.fileName