MySQL 匹配任何集合是子查询



我为此查询寻找更好的解决方案:

SELECT * FROM USER 
WHERE 
1 IN (SELECT some_id...) OR 
2 IN (SELECT some_id...) OR 
3 IN (SELECT some_id...)

子查询可以返回多于 1 行。

我试图将其更改为:WHERE (1,2,3) IN (SELECT some_id...)但它的抛出错误:

操作数应包含 1 列

我尝试了一些技巧,例如:

(1,2,3) = ANY (SELECT some_id...)- 但仍然是同样的问题。

子查询的结果仅从第二个表中some_ids。

是否有任何可能的解决方案可以在没有多个OR的情况下实现这一目标?

感谢您的帮助。

我想你正在寻找:

select u.*
from users u
where exists (select 1
from usercategories uc
where uc.userid = u.userid and
uc.categoryid in (1, 2, 3)
);

如果你真的想使用in,你可以做:

select u.*
from users u
where u.userid in (select uc.userid
from usercategories uc
where uc.categorid in (1, 2, 3)
);

这是你想做的吗?

从用户中选择 * some_id (1, 2, 3) 中的位置

你试过这样的事情吗?(不带子查询)

select user.* from user
join user_category on user.id = user_category.id_user
where user_category.category_id in (1,2,3);

如果您只想检查行是否存在,则可以使用EXISTS,例如:

SELECT * FROM USER u
WHERE EXISTS (
SELECT 1 FROM your_table WHERE some_id IN (1,2,3) AND userid = u.id;
);

最新更新