2014-06-06 77 views
0

我有選擇的某些行,我希望它也選擇行以下我選擇的每一行的SQL,我無法弄清楚如何寫這樣的查詢...SQLite的聯接不工作

簡單的選擇:

SELECT myIndex, scr, date from history where x.state = "Move to Test" 

我的最新嘗試:

SELECT myIndex, scr, date 
from history as x cross join history as y on y.myIndex + 1 = x.myIndex 
where state = "Move to Test" 

其中給出:「曖昧列名:myIndex「

如果我要指定這樣的列表;

SELECT x.myIndex, x.scr, x.date 
from history as x cross join history as y on y.myIndex + 1 = x.myIndex 
where x.state = "Move to Test" 

我什麼也沒有從「Y」表在所有被選擇......

這裏是什麼我的輸出應該看起來像一個例子:

391 200024 2006-11-27 16:03:43  Move to Test  < I am selecting this row 
392 200024 2006-11-27 16:21:02  Dev    < I want to also select the *next* row, regardless of what's in it 
395 200024 2006-11-29 10:58:17  Move to Test  < selected 
396 200024 2006-11-29 12:10:29  Peer Review  < next 
402 200024 2006-11-30 07:27:51  Move to Test  < selected 
403 200024 2006-11-30 08:26:13  TQA    < next 
408 200024 2007-05-03 08:35:40  Move to Test  < selected 
409 200024 2007-05-03 08:52:53  Dev    < next 

回答

1

只需添加or y.state = "Move to Test"到您的最後一個查詢,並將+更改爲-

+0

該行可能不_have_「移動到測試」。 – Radamand

+0

我已經添加了一些信息給我的OP應該更好地解釋。 – Radamand

+0

即使該行沒有「移動到測試」,這也可以工作,因爲添加該條件會選擇上一行標記爲「移動到測試」的行。 – Dan

0

如果我理解正確你想從兩個表myIndex,那麼爲什麼不使用:

SELECT x.myIndex,y.myIndex x.scr, x.date 
from history as x cross join history as y on y.myIndex + 1 = x.myIndex 
where x.state = "Move to Test" 
+0

我已經添加了一些信息給我的OP,應該更好地解釋 – Radamand

1

在SQLite的3.8.3或更高版本:

WITH indexes AS (SELECT myIndex 
       FROM history 
       WHERE state = 'Move to Test') 
SELECT myIndex, 
     scr, 
     date 
FROM history 
WHERE myIndex  IN indexes 
    OR myIndex - 1 IN indexes 

在早期版本中,您不能使用CTE:

SELECT myIndex, 
     scr, 
     date 
FROM history 
WHERE myIndex  IN (SELECT myIndex FROM history WHERE state = 'Move to Test') 
    OR myIndex - 1 IN (SELECT myIndex FROM history WHERE state = 'Move to Test') 
+0

這個查詢完全是我要求的!但... 現在我發現了一個缺陷,我的原始邏輯... 我需要選擇第一行_following_我的行,不**不具有「移動到測試」作爲狀態。 還要感謝@apomene和Dan – Radamand

+0

由於其上一行*「*」具有「移動到測試」狀態,因此將選擇其他狀態的第一行。顯示一個您認爲不起作用的示例輸入。 –