[英]How to join two tables based on two columns and verifying that one column is existing in both
Let me give an example to understand my issue. 让我举一个例子来理解我的问题。
Saying I have a table A and a table B. The tables can be joined based on the columns (say x and y in both). 说我有一个表A和一个表B。这些表可以基于列(例如x和y)连接在一起。
I want to join both tables based on x and y to find out all rows in table A where the couple (x,y) doesn't exist in the table B. 我想基于x和y联接两个表,以找出表A中表B中不存在夫妇(x,y)的所有行。
What I do now is: 我现在要做的是:
SELECT * FROM A a
LEFT JOIN B b
ON a.x = b.x AND a.y = B.y
WHERE b.x IS NULL AND b.y IS NULL;
And the result is ok... 结果还可以...
But me I want to have couples (x,y) in A that don't exist in B and be sure only for couple where x exist in B... 但是我我想在A中有不存在于B中的对(x,y)并确保只对x在B中存在的对...
Any idea? 任何想法?
I have the idea to do the following: 我有以下想法:
SELECT * FROM A a
LEFT JOIN B b
ON a.x = b.x AND a.y = B.y
WHERE b.x IS NULL AND b.y IS NULL
AND x in (SELECT x FROM B);
And that works but it seems for me not a good way... 那行得通,但对我来说似乎不是一个好方法...
Sample data would be: 样本数据为:
in A, we have (x,y): (1,2) (1,5) (2,3) (3,7) 在A中,我们有(x,y):(1,2)(1,5)(2,3)(3,7)
in B, we have (x,y): (1,4) (1,5) (3,9) 在B中,我们有(x,y):(1,4)(1,5)(3,9)
expected result is: 预期结果是:
(1,2) (3,7) (1,2)(3,7)
Thanks for helping! 感谢您的帮助!
Best Regards 最好的祝福
SELECT A.*
FROM A
WHERE NOT EXISTS (SELECT 1
FROM B
WHERE B.x = A.x
AND B.y = A.y)
AND EXISTS (SELECT 1
FROM B
WHERE B.x = A.x)
This return all rows from A, where 这将从A返回所有行,其中
A(x,y)
A(x,y)
A(x)
A(x)
In my experience, subqueries outside of the FROM
clause have generally poor performance, this would probably be faster: 以我的经验,
FROM
子句之外的子查询通常性能较差,这可能会更快:
SELECT *
FROM (SELECT DISTINCT x FROM B) AS bsAs
INNER JOIN A AS a ON bsAs.x = A.x
LEFT JOIN B AS b ON a.x = b.x AND a.y = B.y
WHERE b.x IS NULL AND b.y IS NULL
;
Edit: Don't forget the DISTINCT
in the subquery, otherwise you'll get your results for each x value duplicated for every instance of that x value in B. 编辑:不要忘记子查询中的
DISTINCT
,否则您将获得B中该x值的每个实例重复的每个x值的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.