mysql - sql子查询中如何使用Union

标签 mysql sql sql-server

select user_id,name, login,lastseen from users where user_id 
in((select friend_id from connections where user_id=1 and connection=1) 
union (select user_id from connections where friend_id=1 and connection=1))

我想做一些这样的工作,但这个查询显示错误。如果我在没有 backets 的情况下独立运行这个子查询,它工作正常。 以及如何重写此查询以提高性能

最佳答案

使用 UNION 跳过 IN,改为执行 EXISTS:

select user_id, name, login, lastseen
from users u
where exists (select 1 from connections c
              where c.connection = 1
                and ((u.user_id = c.friend_id and c.user_id = 1) or
                     (c.user_id = u.user_id and c.friend_id = 1)))

关于mysql - sql子查询中如何使用Union,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551934/

相关文章:

java - PreparedStatement 带参数的最大查询未在 Java 中执行

mysql - 在mysql中创建复合字段

sql - 哪个查询的性能更好?

mysql - 具有不同数据的 3 类用户

sql-server - 数据库约束违规错误处理

android - 在 SQL Server 中存储 JSONArray 的 Web 服务

php - 使用 cron 作业每分钟将新行插入表中

php - 数据库 - 当我们尝试插入时查询失败

mysql - 如何获取mysql中日期范围内一周中特定天数的计数?

SQL Server 2008 OPENROWSET权限问题