在同一个表中的两行之间查找匹配的列数据

时间:2012-10-12 08:55:40

标签: sql database sqlite

我想在同一个sqlite表中找到两行之间的匹配值。例如,如果我有下表:

rowid, col1, col2, col3
-----  ----  ----  ----
1      5     3     1    
2      3     6     9    
3      9     12    5

因此比较第1行和第2行,我得到值3。

  • 第2行和第3行将给出9。
  • 第3行和第1行将给出5。

表格中任何两行之间始终只有一个匹配值。

正确的sqlite查询是什么?

2 个答案:

答案 0 :(得分:1)

我硬编码了行的值,因为我不知道如何在sqllite中声明变量。

select t1.rowid as r1, t2.rowid as r2, t2.col as matchvalue from <yourtable> t1 join
(
  select rowid, col1 col from <yourtable> where rowid = 3 union all
  select rowid, col2 from <yourtable> where rowid = 3 union all
  select rowid, col3 from <yourtable> where rowid = 3
) t2
on t2.col in (t1.col1, t1.col2, t1.col3)
and t1.rowid < t2.rowid -- you don't need this if you have two specific rows
and t1.rowid = 1

答案 1 :(得分:0)

select col from
(    
    select rid, c1 as col from yourtable
    union
    select rid, c2 from yourtable
    union
    select rid, c3 from yourtable
) v
where rid in (3,2)
group by col
order by COUNT(*) desc
limit 1