我有两张这样的表:
table1 table2
id COL1 COL2 id COL1 COL2
1 1 2 1 1 2
1 3 4 1 3 4
1 1 5 6
1 2 7 8
2 1 2 2 1 2
2 3 4 2 3 4
2 5 6 2 5 6
2 7 8 2 7 8
我想找到与第二个表
的id匹配所有行的id当我在hana中查询时,我得到两个id
由于只有一个id,即2匹配所有第二个表的行,我期待id为2。
我尝试了所有加入。请帮帮我。
答案 0 :(得分:0)
您可以使用join
来获取两个表之间的匹配行。然后按id聚合并验证计数是否匹配:
select t1.id
from table1 t1 join
table2 t2
on t1.id = t2.id and t1.col1 = t2.col1 and t1.col2 = t2.col2
group by t1.id
having count(*) = (select count(*) from table1 tt1 where tt1.id = t1.id) and
count(*) = (select count(*) from table2 tt2 where tt2.id = t1.id);
另一种方法是使用union all
和聚合:
select id
from (select id, col1, col2, 1 as from1, NULL as from2 from table1 union all
select id, col1, col2, NULL, 1 table2
) t
group by id
having count(*) = sum(from1) and
count(*) = sum(from2);
答案 1 :(得分:0)
我会查找table2中缺少记录的id,然后返回不在该列表中的id列表:
SELECT DISTINCT table1.id
FROM table1 table1
WHERE table1.id NOT IN (
SELECT t1.id
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
AND t1.col1 = t2.col1
AND t1.col2 = t2.col2
WHERE t2.id IS NULL
)
答案 2 :(得分:0)
SELECT *
FROM Table1 t1
WHERE NOT EXISTS (SELECT *
FROM Table1 t11
WHERE t1.id = t11.id
EXCEPT
SELECT *
FROM Table2 t2
WHERE t2.id = t1.id AND t2.COL1=t1.COL1 AND t2.COL2=t1.COL2)
这里的诀窍是,您可以在table1
中找到所有记录,并从EXCEPT
中减去(使用table2
)这些记录。现在,所有字段与id
匹配的table2
将返回NULL
,因此NOT EXISTS
将为您返回此记录。
答案 3 :(得分:0)
我是通过id使用字符串聚合组来完成的。
之后,我使用Id条件比较列