我有一个名为 Customer 的表,其中有两列:CustomerID 和 CustomerName。如下图
declare @customer table (CustomerID INT, CustomerName VARCHAR(10))
INSERT INTO @customer VALUES (1, 'Shane'), (2, 'Daniel'), (3, 'Karim'), (4, 'Eric'), (5, 'Zoe'), (6, 'Jack')
还有另一个名为 Age 的表,它有两列:CustomerID 和 Age。
declare @age table (CustomerID INT, Age INT)
INSERT INTO @Age VALUES (1, 20), (2, 19), (3, 12), (6, 30)
现在,我想在 Customer 表上添加一个名为 HasAge 的附加列,如果 Customer 表中的 CustomerID 也存在于 Age 表中,则返回 1,否则返回 0。
我尝试使用左连接和 CTE 来获得结果。所以我想知道是否有另一种方法可以做到这一点(不使用连接)。例如。在 select 语句中使用子查询。事实上,对我来说,真实的情况要复杂得多。为了演示,我使用更简单的示例。我的目标不是使用连接和 CTE,所有这些都在单个查询或其他神奇函数中完成(也许存在?)。感谢您的帮助!
最佳答案
左连接
简洁、优雅、高效:
select c.*, (case when a.customerid is null then 0 else 1 end) as has_age
from @customer c left join
@age a
on c.customerid = a.customerid;
也就是说,这样的查询通常使用 casewhenexists
编写,以防多行匹配:
select c.*
(case when exists (select 1 from @age a where c.customerid = a.customerid)
then 1 else 0
end) as has_age
from @customer c;
这也是优雅、简洁、高效的。如果您知道最多有一行匹配,许多人会更喜欢 left join
版本。就我个人而言,我是中立的。
当我说“高效”时,我的意思是性能是可以预期的最好的。为了获得真正的性能,您需要在 age(customerid)
上建立索引。两个查询都可以使用这样的索引。
关于SQL:通过连接将一个表中的列链接到另一个表中的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50051101/