Cardinality violation when using a subquery that returns two values

不问归期 提交于 2020-01-06 02:44:07

问题


I have create a sql query that the sketch is like this

select *
from   A
where  A.id in (select  B.id1, B.id2 from B);

where the main select returns those values for which A.id coincides with either B.id1 or B.id2.

Clearly this solution doesn't work as the cardinality doesn't match in the where clause. How can I overcome this problem?

One solution would be to make two sub-queries, one for B.id1 and one for B.id2, but as my sub-query is much longer than in this example I was looking for a more elegant solution.

I'm using Mysql

EDIT 1 As long as the syntax is simpler than using two sub-queries I have no issues using joins

EDIT 2 Thanks @NullSoulException. I tried the first solution and works as expected!!


回答1:


Something like the below should do the trick.

select * 
From table1 a , (select id1 , id2 from table2 ) b 
where (a.id = b.id1) or  (a.id = b.id2)

or you can JOIN with the same table twice by giving the joined tables an alias.

select * from table1 a 
INNER JOIN table2 b1 on a.id = b1.id1
INNER JOIN table2 b2 on a.id = b2.id2

Please test the above against your datasets/tables..



来源:https://stackoverflow.com/questions/35608920/cardinality-violation-when-using-a-subquery-that-returns-two-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!