- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有两个表:IndustryCustomers 和 ProductCustomers,它们具有相同的架构,只有这样一列
行业客户:
产品客户:
所以我想要的是:
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/
所以,我有一个类似于 this one 的用例,但我觉得有一些额外的细节值得提出一个新问题。 ( related questions ,供引用) 我正在编写一个实现 a cycle 的数据结构.基本设
我正在使用 Django 编写一个社交网络应用程序,需要实现类似于 Facebook“Mutual Friends”概念的功能。我有一个像这样的简单模型: class Friend(models.Mo
我有一个 iOS 应用程序,用户可以在其中使用 Facebook 登录并授予 user_friends 权限。从 Graph API 2.0 开始,Facebook 声称你无法获取两个人之间所有的共同
我想知道将来对我来说最简单的方法是什么,可以使查询既有效又不那么复杂。 我应该像这样保存双向关系吗 from_id=1, to_id=2from_id=2, to_id=1 或者只创建一个唯一的行 f
我是一名优秀的程序员,十分优秀!