sql - 根据特定条件选择连接表的不同列
问题描述
我想在加入多个表后根据特定条件检索两列的单行。用例子来解释它,我有这个:
SELECT c.column1, c.column2, d.column3, d.column4
FROM table1 a
JOIN table2 b ON a.id=b.id
JOIN table3 c ON b.tabid = c.tabid
LEFT JOIN table4 d ON c.pmid=d.pmid
WHERE a.id = @id
在 column1 和 column2 不为 NULL 的情况下,我希望将其中两个检索为
SELECT c.column1, c.column2
FROM table1 a
JOIN table2 b ON a.id=b.id
JOIN table3 c ON b.tabid = c.tabid
LEFT JOIN table4 d ON c.pmid=d.pmid
WHERE a.id = @id
否则,我想拥有
SELECT d.column3, d.column4
FROM table1 a
JOIN table2 b ON a.id=b.id
JOIN table3 c ON b.tabid = c.tabid
LEFT JOIN table4 d ON c.pmid=d.pmid
WHERE a.id = @id
我将使用带有 COUNT 函数的 IF 子句首先单独查看列是否为空,然后使用普通的 SELECT 语句进行检索。但是从同一个表中读取 3 次将是三重工作(检查每列的计数是否 > 0;如果两者都为真,则从这些列中进行选择)。我相信它可以更好地增强。
我还考虑使用两个单独的公用表表达式来与 CASE 一起使用。但最终出现语法错误。
任何指导将不胜感激。谢谢!
解决方案
您可以使用 case 语句确定从查询中输出哪些列。如果两者都为空,则输出第 3 列和第 4 列,如果不是,则输出第 1 列和第 2 列。您可能需要更改输出的内容。
SELECT
case when isnull(c.column1,'') = '' and isnull(c.column2,'') = ''
then c.column1 + c.column2 else c.column3 + c.column4 end as 'Column'
FROM table1 a
JOIN table2 b ON a.id=b.id
JOIN table3 c ON b.tabid = c.tabid
LEFT JOIN table4 d ON c.pmid=d.pmid
WHERE a.id = @id
对于上述答案,如果输出中的任何列可能为空,则需要将输出中的每一列包装在 isnull 语句中,以避免将两列的值都归零。
如果您想要两个单独的列输出,请使用两个 case 语句:
SELECT
case when isnull(c.column1,'') = '' and isnull(c.column2,'') = ''
then c.column1 else c.column3 end as 'Column1',
case when isnull(c.column1,'') = '' and isnull(c.column2,'') = ''
then c.column2 else c.column4 end as 'Column2'
FROM table1 a
JOIN table2 b ON a.id=b.id
JOIN table3 c ON b.tabid = c.tabid
LEFT JOIN table4 d ON c.pmid=d.pmid
WHERE a.id = @id
您可能需要调整 case 语句,我认为 SQL 2014 中有更好的方法(我现在陷入 SQL 2018 R2 模式)。
推荐阅读
- javascript - 我可以使用 forEach 更改许多变量吗?
- python - Django期初余额计算
- javascript - 如何将 JSON 数据插入表单字段
- regex - 正则表达式 - 如何确保字符串末尾没有点?
- java - 如何在java中检查a html标签是否有结束标签?
- angular - Angular6(点击)在div的情况下不传递事件
- python - Python markdown 强制执行
- 无需前面的空行
- angular - x分钟后如何在没有用户交互的情况下刷新角度页面?
- airflow - 气流 apply_defaults 装饰器报告 参数是必需的
- wordpress - 使用 nginx 将搜索页面重定向到搜索结果页面