sql - 根据 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
解决方案
使用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)
推荐阅读
- php - 无法在功能测试中设置查询字符串
- variables - 如何在 mxnet 中初始化符号变量
- wildfly - Drools 与 Java 11 的兼容性
- web-scraping - 运行 Scrapoxy 和 Digital Ocean 的问题
- spring-boot - 从 IntelliJ 启动应用程序时,H2 控制台未在 Spring Boot 应用程序中打开
- angular - 如何在角度组件之间传递数据?
- java - 膨胀 android.support.v7.widget.CardView 抛出错误
- angular - 从不同的组件调用服务以显示消息
- javascript - 如果图像交换应用程序的 src 不存在,则跳过图像并移至下一个
- python - 如何使用 matplotlib 以乳胶形式显示 f.__doc__?