Mysql - 获取没有以前状态的行

时间:2016-01-08 09:22:59

标签: mysql sql

我有一张表来保持Sample状态。

 id     sample_id               previous_status     current_status  
 1      22216                   NULL                    1   
 2      22216                   1                       3   
 3      22221                   NULL                    1   
 4      22221                   1                       3   

我想找到当前状态中没有条目的行为1。

编辑(来自评论): 我想要样本ID,其中previous_status = 1,当前状态= 3,没有行,previous_status = null,current_status = 1。

2 个答案:

答案 0 :(得分:2)

  

我想要样本ID,其中previous_status = 1,当前状态= 3且没有行,previous_status = null,current_status = 1

您可以使用相关子查询:

SELECT s1.sample_id
FROM Sample s1
WHERE previous_status = 1
  AND current_status = 3
  AND NOT EXISTS (SELECT 1
                  FROM Sample s2
                  WHERE s2.sample_id=s1.sample_id
                    AND s2.previous_status IS NULL
                    AND s2.current_status = 1);

SqlFiddleDemo

使用GROUP BY

SELECT sample_id
FROM Sample
GROUP BY sample_id
HAVING SUM(previous_status = 1 AND current_status = 3) > 0
   AND SUM(previous_status IS NULL AND current_status = 1) = 0;

SqlFiddleDemo2

答案 1 :(得分:-1)

尝试,

Select * from Sample where previous_status =1 and current_status = 3 and previous_status  IS NOT NULL and current_status <>1

其中<>不等于

http://sqlfiddle.com/#!9/1c9f55/9 (采取小伙子的方式)