sql-server - SQL 是 LEFT JOIN 和 WHERE 语句的最佳替代方案?
问题描述
基本上我有两张桌子。客户和采购表。我的问题是购买表非常大并导致性能问题,我试图将我的代码组织到相关的 CTE 中。
我正在尝试为那些购买了 A 型吉他或没有购买的人提取所有购买记录。
我想过滤掉任何没有购买 GuitarType A但仍保留没有购买任何东西的客户。
这是我的代码:
WITH Purchases AS
(
SELECT
, CustID
, GuitarType
FROM
Purchase
WHERE
GuitarType = 'A'
)
,
RelevantCustomers AS
(
SELECT
P.Custid
, P.PurchaseDate
, C.CustType
FROM
Customer
)
SELECT
Custid
, GuitarType
, PurchaseDate
FROM
Purchases AS p
INNER JOIN
RelevantCustomers AS rc ON p.CustId= rc.CustId
顾客:
+--------+-------------+----------+
| CustId | CreatedDate | CustType |
+--------+-------------+----------+
| 1 | 01/01/2017 | A |
+--------+-------------+----------+
| 2 | 01/01/2018 | B |
+--------+-------------+----------+
| 4 | 01/01/2018 | C |
+--------+-------------+----------+
购买
+----------+--------------+------------+
| GuitarId | PurchaseDate | GuitarType |
+----------+--------------+------------+
| 1 | 04/01/2018 | A |
+----------+--------------+------------+
| 1 | 05/01/2018 | A |
+----------+--------------+------------+
| 1 | 06/01/2018 | C |
+----------+--------------+------------+
| 2 | 06/01/2018 | A |
+----------+--------------+------------+
| 2 | 06/01/2018 | B |
+----------+--------------+------------+
| 2 | 06/01/2018 | A |
+----------+--------------+------------+
如果我使用 INNER JOIN 那么它只会返回那些购买 Guitar Type A 的人。如果我使用 LEFT 那么它将包括所有客户。
One alternative is to move the "Where GuitarType = 'A' down to the where clause and do a LEFT JOIN but this will cause my code to be unorganized and potentially some performance issues.
解决方案
This might do it
SELECT rc.Custid, p.GuitarType, p.PurchaseDate
FROM RelevantCustomers rc
LEFT JOIN Purchases p
ON p.CustId = rc.CustId
LEFT JOIN Purchases pn
ON pn.CustId = rc.CustId
AND p.GuitarType != 'A'
WHERE (p.GuitarType = 'A' OR p.CustID IS NULL)
and pn.CustID is null
推荐阅读
- folium - folium choropleth 返回空白
- android-recyclerview - 我在片段中添加了 Recycler 视图,现在我正在尝试将图像传递给 recycler 视图,但是应用程序在 logcat 上因错误消息而崩溃
- abap - 在 OO 上下文中,PACK 的等价物是什么?
- select - 有没有办法在使用 ffmpeg 的选择过滤器时包含过渡视频?
- unity3d - 使用 Unity 3D 移动鼠标时相机跟随玩家
- javascript - Blaze 模板,遍历字段?
- reactjs - 为什么“禁用:”顺风前缀在我的反应应用程序中不起作用?
- python - Pygame 在点击之间重置计时器
- routes - 在 Raspberry Pi 4 上添加静态 ip 路由/规则
- javascript - 使用 AJAX(JavaScript 和 PHP)发送邮件表单不起作用