我有sql查询,它接受一个Key并输出一组记录{S}。
如何创建一个SQLite递归查询,该查询接受一组N个键,返回所有集合的交集{{S1},{S2},{S3}}
无需生成复制/粘贴的SQL语句。
我举一个简单的例子。所以这是交叉的明显答案。
SELECT record from RecordSet where key = 'KEY1'
INTERSECT
SELECT record from RecordSet where key = 'KEY2'
我不想做的是像这样复制和粘贴:
SELECT record from RecordSet where key = 'KEY1'
INTERSECT
SELECT record from RecordSet where key = 'KEY2'
INTERSECT
SELECT record from RecordSet where key = 'KEYN'
而是使用这里看到的递归查询功能: WITH RECURSIVE Example Here Under Recurisve Query Example
我可以传递所有密钥
SELECT key from KEYS where key in (KEY1, KEY2, KEY3, ..., KEYN)
To this recursive query.
答案 0 :(得分:1)
尝试这样的查询:
WITH abc AS(
SELECT Kej, val,
(SELECT count(DISTINCT kej) FROM mytable b WHERE b.kej < a.kej) As cnt
FROM mytable a
),
bcd AS (
SELECT * FROM abc WHERE cnt = (SELECT max(cnt) FROM abc)
UNION ALL
SELECT a.* FROM abc a
JOIN bcd b ON a.cnt = b.cnt - 1
AND a.val = b.val
)
SELECT val FROM bcd
WHERE cnt = 0
演示:SQL Fiddle 上述查询的工作原理是只检查了一个列以进行交集 如果您的表有N个列(val1,val2,... valN),则连接必须包含所有这些列:
JOIN bcd b ON a.cnt = b.cnt - 1
AND a.val1 = b.val1
AND a.val2 = b.val2
.....
AND a.valN = b.valN