2016-04-27 31 views
-1

我想檢查一行中是否有四個相同的值(我的意思是一個接一個,而不是表中的一行)。所以,如果我檢查的價值「附件」,下面的查詢結果將是錯誤的:檢查一個查詢是否在MySQL中返回了4個連續的相同值

type_count post_type 
1    post 
2    attachment 
3    post 
4    post 
5    attachment 
6    post 
7    attachment 
8    post 
9    post 
10   post 
11   post 
12   attachment 
13   post 
14   post 
15   post 

鑑於此數據集將被證明是正確的:

type_count post_type 
1    post 
2    attachment 
3    post 
4    post 
5    attachment 
6    attachment 
7    attachment 
8    attachment 
9    post 
10   post 
11   post 
12   attachment 
13   post 
14   post 
15   post 

這可能嗎?從查詢結果而不是表格開始工作。

+0

是遊標和存儲過程接受? – cantSleepNow

+0

@cantSleepNow - 如果可能,寧願用查詢來做。 – BFWebAdmin

回答

3

如果下面的查詢:

SELECT COUNT(*) 
FROM (
    SELECT type_count, post_type, 
     @seq := IF(@pt = post_type, @seq+1, 
        IF(@pt := post_type, 1, 1)) AS seq 
    FROM mytable 
    CROSS JOIN (SELECT @seq := 0, @pt := '') AS vars) AS t 
WHERE post_type = 'attachment' AND seq >= 4 

返回一個數字,等於或大於1,那麼你的標準是真,否則爲false。

如果你想找到一個查詢結果,而不是一個表內的序列,使用派生表,如FROM (select * from table2) AS mytable

+0

它的工作,它很快!謝謝。 – BFWebAdmin

0

假設type_count是連續的,你可以使用EXIST和簡單JOIN

SELECT CASE WHEN EXISTS (SELECT 1 
         FROM mytable m1 
         JOIN mytable m2 
          ON m2.type_count = m1.type_count + 1 
         JOIN mytable m3 
          ON m3.type_count = m1.type_count + 2 
         JOIN mytable m4 
          ON m4.type_count = m1.type_count + 3 
         WHERE m1.post_type = 'attachment' 
          AND m2.post_type = 'attachment' 
          AND m3.post_type = 'attachment' 
          AND m4.post_type = 'attachment') 
      THEN 1 
      ELSE 0 END AS result 

LiveDemoLiveDemo2

輸出:0(假)和1(真)

相關問題