【问题标题】:Selecting different columns of joined tables based on certain criteria根据特定条件选择连接表的不同列
【发布时间】:2019-08-03 00:11:26
【问题描述】:

我想在连接多个表后根据特定条件检索两列的单行。用例子来解释它,我有这个:

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 一起使用。但最终出现语法错误。

任何指导将不胜感激。谢谢!

【问题讨论】:

  • 您使用的是什么关系型数据库?可以使用IsNull()COALESCE() 函数吗?
  • SQL 2014。我可以使用它。但我必须检查两列是否都不是 NULL。
  • 如果其中 1 个为空,那是什么?
  • 如果c.column1、c.column2之一为null,我就取d.column3、d.column3。

标签: sql sql-server tsql select sql-server-2014


【解决方案1】:

您可以使用 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 模式)。

【讨论】:

  • 我认为 OP 想要单独的列,而不是合并的列。
  • 我最初回答为两列,然后在重读后更新为一列。我将更新以处理这两种情况。
  • 列应单独检索。未连接。
  • @kenean,我调整以回答串联和单独的列返回。
  • 我认为这应该可行。但是仍然可以简单地使用带有 IS NOT NULL 的 CASE 语句来避免 ISNULL。谢谢。
【解决方案2】:

我认为这可以满足您的需求:

select 
  case when c.column1 is null or c.column2 is null then d.column3 else c.column1 end,
  case when c.column1 is null or c.column2 is null then d.column4 else c.column2 end
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

检查两次是相同的条件。

【讨论】:

  • @WEI_DBA 它应该是“和”而不是“或”,因为两列都应该为空
  • @forpas 已更正!我的错。谢谢。
  • @SteveB,在 cmets 中阅读 OP 对 fopas 问题的回答。
猜你喜欢
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 2012-10-03
相关资源
最近更新 更多