1

考虑表格

          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_1Record_4Bill包含在Col_2以前的记录中。

是否可以编写执行此操作的 SQL 查询?

4

2 回答 2

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)
于 2013-09-05T17:47:51.340 回答
0

SQL小提琴

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`))

结果

| INDEX | COL_1 | COL_2 | VALUE_OF_INTEREST |
|-------|-------|-------|-------------------|
|     3 |   Tom |   Rob |                 1 |
于 2013-09-05T17:58:21.557 回答