2016-01-08 31 views
1

我有一个表保持Sample状态。Mysql - 获得没有以前状态的行

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

我想找到这在目前的状况没有条目1

编辑(从评论)该行: 我想这有PREVIOUS_STATUS = 1,现状样品ID = 3和NO行与PREVIOUS_STATUS = NULL,CURRENT_STATUS = 1

+0

我想这有PREVIOUS_STATUS = 1,当前状态= 3的样品ID和与PREVIOUS_STATUS没有行= null,current_status = 1 –

回答

2

我想具有PREVIOUS_STATUS = 1,当前状态= 3和NO行与PREVIOUS_STATUS = NULL,CURRENT_STATUS = 1

样品ID

你可以使用相关子查询:

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

'为空'或'不是空'? – Dhara

+0

@debin'IS NULL' :) – lad2025

+0

'没有行与previous_status = null,current_status = 1'然后根据你的jsfiddle它必须是2记录..不是吗? – Dhara

-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 (采取童子的sqlfiddle)