gpt4 book ai didi

sql - 根据条件获取两个表之间的共同记录

转载 作者:行者123 更新时间:2023-12-02 15:56:02 26 4
gpt4 key购买 nike

假设我有两个表:IndustryCustomersProductCustomers,它们具有相同的架构,只有这样一列

行业客户:

<表类="s-表"><头>客户编号<正文>123

产品客户:

<表类="s-表"><头>客户编号<正文>234

所以我想要的是:

1- 如果 industryCustomers 和 productCustomers 都有记录,那么在它们之间获取共同的客户(只需通过内连接 customerId)

2- 如果 industryCustomers 有任何记录但 productCustomer 没有记录则选择所有 industryCustomers

3-如果industryCustomers没有任何记录则选择所有产品客户

目前我使用 IF 来做到这一点并根据条件进行选择,但我想知道是否可以通过一次查询获得客户。

这是我的查询

IF EXISTS (SELECT TOP 1 1 FROM #IndustryCustomers)
BEGIN
IF EXISTS (SELECT TOP 1 1 FROM #ProductCustomers)
SELECT *
FROM #IndustryCustomers ic
JOIN #ProductCustomers pc
ON ic.CustomerId = pc.CustomerId;
ELSE
SELECT *
FROM #IndustryCustomers;
END;
ELSE
SELECT *
FROM #ProductCustomers;

最佳答案

您可以UNION ALL 您的三个SELECT 并将相应的条件放在WHERE 子句中,例如

SELECT ic.CustomerId 
FROM #IndustryCustomers AS ic
INNER JOIN #ProductCustomers AS pc ON ic.CustomerId = pc.CustomerId
WHERE EXISTS (SELECT 1 FROM #IndustryCustomers)
AND EXISTS (SELECT 1 FROM #ProductCustomers)

UNION ALL

SELECT ic.CustomerId
FROM #IndustryCustomers AS ic
WHERE EXISTS (SELECT 1 FROM #IndustryCustomers)
AND NOT EXISTS (SELECT 1 FROM #ProductCustomers)

UNION ALL

SELECT pc.CustomerId
FROM #ProductCustomers AS pc
WHERE NOT EXISTS (SELECT 1 FROM #IndustryCustomers)

显然,这需要所有三个 SQL 返回同一组列,因此我将 * 简化为客户 ID。

不过,我确实认为这个“解决方案”虽然形式上满足了您的要求,但可读性不如您当前的解决方案...

关于sql - 根据条件获取两个表之间的共同记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71526004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com