首页 > 解决方案 > 根据 SQL 中的值选择两列之一

问题描述

我有一个场景,我有一个用户表,其中用户根据连接表相互连接。连接表有一个 user_id1 字段和一个 user_id2 字段。

我想获取特定用户的连接:

select id, user_id1, user_id2 
from connections 
where user_id1 = 1 or user_id2 = 1

但是连接的 user_id 被分成两列。如何在一列中获取特定用户的连接。

我已经尝试过了,但没有奏效:

select user_id1 or user_id2 
from 
    (select id, user_id1, user_id2 
     from connections 
     where user_id1 = 1 or user_id2 = 1) as con 
where user_id1 != 1 and user_id2 != 1

标签: sql

解决方案


使用CASE表达式:

SELECT CASE user_id1
         WHEN 1 then user_id2 
         ELSE user_id1
       END AS user_id
FROM connections 
WHERE 1 IN (user_id1, user_id2)

推荐阅读