我有
ID Rank
11 1
11 2
22 1
22 2
22 3
33 1
33 3
44 1
55 1
55 2
我想要
11
44
55
也就是说,我想只返回从未在等级为'3'的ID。
更新 - 除了下面的答案之外,我想到了另一种方式,相当简单。
SELECT ID FROM
(
SELECT ID, SUM(CASE WHEN Rank = 3 THEN 1 ELSE 0 END) flag FROM
(
SELECT ID, Rank FROM T1
) a
GROUP BY ID
) b
WHERE flag = 0;
答案 0 :(得分:2)
使用NOT EXISTS
:
SELECT DISTINCT
yt1.ID
FROM
yourTable yt1
WHERE
NOT EXISTS (
SELECT *
FROM yourTable yt2
WHERE
yt1.ID = yt2.ID
AND yt2.Rank = 3
)
或者,使用LEFT JOIN
:
SELECT DISTINCT
yt1.ID
FROM
yourTable yt1
LEFT JOIN yourTable yt2 ON yt1.ID = yt2.ID AND yt2.Rank = 3
WHERE
yt2.ID IS NULL
答案 1 :(得分:0)
我会制作一系列独特的ID,然后检查三个等级。那些没有的,将它们放入最终阵列。
$idArray = array();
$noThreeArray = array();
$query = 'SELECT DISTINCT ID FROM yourTable';
while($row = mysql_fetch_array($query)){
$idArray[] = $row['ID'];
}
foreach($idArray as $id){
$query = 'SELECT ID FROM yourTable WHERE ID = $id AND Rank = 3';
if(mysql_num_rows($query) == 0){
$noThreeArray[] = $row['ID'];
}
}
$ noThreeArray现在拥有你所追求的价值。
答案 2 :(得分:0)
SELECT ID FROM
(
SELECT ID, SUM(CASE WHEN Rank = 3 THEN 1 ELSE 0 END) flag FROM
(
SELECT ID, Rank FROM T1
) a
GROUP BY ID
) b
WHERE flag = 0;
答案 3 :(得分:-1)
select ID as IDS from table where rank != 3 group by table.ID;