首页 > 解决方案 > SQL:如果子查询中存在或不存在多个值,则返回真/假

问题描述

我有一个表,其中有两列是外键(例如在 userID(int) 中考虑:orderID(int)),我必须知道用户 ID 是否存在订单 2、3、4、5,在 where大查询的子句。

我需要优化我的数据库

SELECT table1.myrow FROM table1, table2
WHERE table1.myrow = table2.myrow
AND 1 IN (SELECT myRoww from table2 WHERE table2.id = table1.myrow)
AND 2 IN (SELECT myRoww from table2 WHERE table2.id = table1.myrow)
AND 3 IN (SELECT myRoww from table2 WHERE table2.id = table1.myrow)

我想做这样的事情:

 AND (SELECT * from mytable) IN (SELECT myRoww from table2 WHERE table2.id = table1.myrow)

如何确定某个 ID 是否存在我的多值列表?我请求的行是仅包含在具有两个外键的表中的关系。

我的关系:

关系模型

需要知道 CONVOCATORIA_SECTOR 是否与 CONVOCATORIAS(id_bdns_Conv) 有 X 关系

标签: mysqlsqldatabase

解决方案


您可以通过按用户 ID 和 HAVING 子句中的条件进行分组来实现:

select userid
from tablename
where orderid in (2,3,4,5)
group by userid
having count(distinct orderid) = 4

这将选择所有userid存在orderids 2、3、4 和 5 的 s。


推荐阅读