SQLite选择和跨列匹配

时间:2012-10-24 22:09:55

标签: sql sqlite

我有一个名为match的SQLite表,它有两列:column1和column2,包含整数值:

column1   column2
------------------

5          6
6          8
8          9
90         91
1          20
10         20

我希望匹配在任一列中找到的重复数字并加入它们,包括匹配第二个值,以便我的搜索结果返回:

5, 6, 8, 9 
1, 20, 10

(注意90和91没有匹配,因此不包括在内)。

我对此做出的'猜测'是:

SELECT column1, column2 
FROM match 
WHERE column2 
IN (SELECT column1 
    FROM match 
    GROUP BY column1 HAVING (COUNT(column1) > 0)) 
    UNION 
    SELECT column1, column2 
    FROM match 
    WHERE column1 
    IN (SELECT column2 
        FROM match 
        GROUP BY column1 HAVING (COUNT(column2) > 0)) 
        UNION 
        SELECT column1, column2 
        FROM match 
        WHERE column1 
        IN (SELECT column1
            FROM match 
            GROUP BY column1 HAVING (COUNT(column1) > 1)) 
            UNION 
            SELECT column1, column2 
            FROM match 
            WHERE column2 
            IN (SELECT column2 
                FROM match 
                GROUP BY column2 HAVING (COUNT(column2) > 1)) 

结果几乎是我所需要的:

5 6
6 8
8 9
1 20
10 20

但我真正需要的是以某种方式对结果进行分组。例如:

(5,6,8,9)(1,10,20)

这可能吗?我的SQL尝试是否过于复杂?

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:http://sqlfiddle.com/#!7/05747/9

SELECT column1 as newColumn
FROM match WHERE column1 in (

SELECT myColumn
FROM(

SELECT count(*) as cnt, myColumn
FROM (
SELECT column1 as myColumn
FROM match
UNION ALL
SELECT column2 as myColumn
FROM match
 ) x
GROUP BY myColumn
HAVING cnt > 1
  ) y
) OR column2 in (
SELECT myColumn
FROM(

SELECT count(*) as cnt, myColumn
FROM (
SELECT column1 as myColumn
FROM match
UNION ALL
SELECT column2 as myColumn
FROM match
 ) x
GROUP BY myColumn
HAVING cnt > 1
  ) y
)
UNION
SELECT column2 as newColumn
FROM match WHERE column1 in (

SELECT myColumn
FROM(

SELECT count(*) as cnt, myColumn
FROM (
SELECT column1 as myColumn
FROM match
UNION ALL
SELECT column2 as myColumn
FROM match
 ) x
GROUP BY myColumn
HAVING cnt > 1
  ) y
) OR column2 in (
SELECT myColumn
FROM(

SELECT count(*) as cnt, myColumn
FROM (
SELECT column1 as myColumn
FROM match
UNION ALL
SELECT column2 as myColumn
FROM match
 ) x
GROUP BY myColumn
HAVING cnt > 1
  ) y
)