MYSQL /按2列关系选择查询

时间:2014-09-26 19:03:23

标签: mysql select group-by

我只想选择那些状态等于2的ID。如果同一ID的值也大于2,则应跳过此ID的所有匹配。

如下例所示:



<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>
&#13;
&#13;
&#13; 我的预期结果是&#34; 7&#34;。

3 个答案:

答案 0 :(得分:0)

这将为您提供最高状态为2的所有ID的列表。其结果将是&#34; 7&#34;:

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

答案 1 :(得分: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

答案 2 :(得分: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);