我在PostgreSQL中有一个connection
表,其中每一行都是一对连接的用户:
connection:
id
firstuserid
seconduserid
...
对于给定的用户ID,我想为其所有连接获取其他用户ID。如果我做两个查询,这很明显:
select firstuserid from connection where seconduserid = 123
select seconduserid from connection where firstuserid = 123
有没有办法在一个查询中执行此操作,只返回其他用户ID而不是两者?
答案 0 :(得分:1)
只需使用UNION
select firstuserid from connection where seconduserid = 123
union
select seconduserid from connection where firstuserid = 123
没有UNION
你可以写
select case when firstuserid = 123 then seconduserid
else firstuserid end
from connection
where seconduserid = 123 or firstuserid = 123