考虑表
Index Col_1 Col_2 Value_of_Interest
Record_1 1
Record_2 2
.
.
.
Record_N N
我想选择一组记录{Record_i}
,Col_1
Record_i+1
{SELECT Col_2 FROM table WHERE Index<i}
个 Index Col_1 Col_2 Value_of_Interest
Record_1 1 Ed Bill 1
Record_2 2 James Rob 0
Record_3 3 Tom Rob 1
Record_4 4 Bill Rob 0
例如,考虑表
Index Col_1 Col_2 Value_of_Interest
Record_3 3 Tom Rob 1
查询将返回
Col_1
Record_4
的{{1}}为Bill
,并且包含在之前记录的Col_2
中。
是否可以编写执行此操作的SQL查询?
答案 0 :(得分:2)
SELECT *
FROM MyTable AS T1
WHERE (SELECT Col_1
FROM MyTable AS T2
WHERE T2.Index = T1.Index + 1
) IN (SELECT Col_2
FROM MyTable AS T3
WHERE T3.Index < T1.Index)
答案 1 :(得分:0)
MySQL 5.5.32架构设置:
CREATE TABLE Table1
(`Index` int, `Col_1` varchar(5), `Col_2` varchar(4), `Value_of_Interest` int)
;
INSERT INTO Table1
(`Index`, `Col_1`, `Col_2`, `Value_of_Interest`)
VALUES
(1, 'Ed', 'Bill', 1),
(2, 'James', 'Rob', 0),
(3, 'Tom', 'Rob', 1),
(4, 'Bill', 'Rob', 0)
;
查询1 :
SELECT t1.`Index`, t1.Col_1, t1.Col_2, t1.Value_of_Interest
FROM Table1 t1
WHERE t1.`index` =
(SELECT t2.`index`-1
FROM Table1 t2
WHERE t2.Col_1 IN
(SELECT Col_2 FROM Table1 t3 WHERE t3.`Index` < t2.`Index`))
<强> Results 强>:
| INDEX | COL_1 | COL_2 | VALUE_OF_INTEREST |
|-------|-------|-------|-------------------|
| 3 | Tom | Rob | 1 |