2014-09-26 59 views
0

我只想選擇那些狀態等於2的ID。如果同一個ID的值大於2,那麼這個ID的所有出現都應該跳過。MYSQL /按2列關係選擇查詢

如下面的例子:

<table> 
 
    <tr> 
 
    <td>id</td> 
 
    <td>status</td> 
 
    </tr> 
 
    <tr> 
 
    <td>5</td> 
 
    <td>2</td> 
 
    </tr> 
 
    <tr> 
 
    <td>5</td> 
 
    <td>3</td> 
 
    </tr> 
 
    <tr> 
 
    <td>6</td> 
 
    <td>2</td> 
 
    </tr> 
 
    <tr> 
 
    <td>6</td> 
 
    <td>3</td> 
 
    </tr> 
 
    <tr> 
 
    <td>7</td> 
 
    <td>2</td> 
 
    </tr> 
 
</table>
我預期的結果是 「7」。

回答

0

這就是你需要

select x.id from mytable x where status=2 and NOT EXISTS(Select y.id from mytable y where status > 2 and x.id = y.id); 
+0

謝謝......它的工作正常。 – 2014-09-26 20:08:16

0

這會給你的列表中的所有ID的,其最大的狀態2.其結果將是 「7」:

SELECT ID FROM myTable 
GROUP BY ID 
HAVING MAX(Status) = 2 
+0

沙魯克 - 你可以發佈你的查詢嗎?我的答案中只有一列返回,上面的評論說你回來了兩列。 – 2014-09-26 19:58:12

0
select id 
from table t1 
inner join (select id, count(*) cnt from table group by id) t2 on 
    t2.id = t1.id 
    and t2.cnt = 1 
where status = 2