2016-09-26 29 views
1

例如MYSQL選擇連續記錄都有條件

No   Condition 
1    NULL 
2    O 
3    NULL 
4    NULL 
5    NULL 
6    NULL 
7    NULL 
8    O 
9    NULL 
10    NULL 
11    NULL 
12    O 

什麼是希望選擇具有NULL條件否的SQL和它下面的兩個記錄也有NULL條件?

對於該表,應該選擇3,4,5和9。

回答

1

假設no是連續的,沒有空位 - 在您的樣本數據 - 那麼你可以使用join

select t.no 
from t join 
    t1 
    on t1.no = t.no + 1 join 
    t2 
    on t2.no = t.no + 2 
where t.condition is null and 
     t1.condition is null and 
     t2.condition is null; 
0

假設No字段沒有間隙(如問題所示),自加入你的表3倍增加No價值觀和選擇,所有Condition字段爲空的記錄:

select t1.No 
from yourtable t1 
inner join yourtable t2 on t1.No+1=t2.No 
inner join yourtable t3 on t1.No+2=t3.No 
where t1.Condition is null and t2.Condition is null and t3.Condition is null 
0

一種選擇是使用相關subque以檢索下兩行的條件列的值。例如:

SELECT t1.no 
    FROM mytable t1 
    WHERE t1.condition IS NULL 
    AND (SELECT (t2.condition IS NULL) 
      FROM mytable t2 
      WHERE t2.no > t1.no 
      ORDER BY t2.no 
      LIMIT 0,1 
     ) 
    AND (SELECT (t3.condition IS NULL) 
      FROM mytable t3 
      WHERE t3.no > t1.no 
      ORDER BY t3.no 
      LIMIT 1,1 
     ) 
ORDER BY t1.no 

這不一定會給出最佳性能。但是這是有效的MySQL語法,並且它返回指定的結果集。

這假定如果在No列中有間隙,則意圖是檢查具有較高值No的下兩行。如果說明書僅檢查行No+1No+2,則> t1.no可以替換爲= t1.no + 1= t1.no + 2,並用LIMIT 0,1替換LIMIT 1,1