[英]Avoid an additional subselect in this UNION query?
shipping_customer
表:
+----+---------------+---------------------+
| id | business_name | billing_customer_id |
+----+---------------+---------------------+
| 1 | Soylent Corp | 3 |
| 2 | Initech | 4 |
+----+---------------+---------------------+
billing_customer
表:
+----+--------------------+
| id | business_name |
+----+--------------------+
| 3 | Acme Corporation |
| 4 | Globex Corporation |
+----+--------------------+
在兩個表中,ID是唯一的。 期望的輸出是id IN (1, 4)
每個客戶(如果要運輸,還選擇開票客戶id IN (1, 4)
:
+-------------+--------------------+----------+
| id | business_name | type |
+-------------+--------------------+----------+
| 1 | Soylent Corp | shipping |
| 3 | Acme Corporation | billing | <- 1 has billing_customer = 3
| 4 | Globex Corporation | billing |
+-------------+--------------------+----------+
有辦法避免子選擇嗎?
SELECT id, business_name, 'shipping' AS type
FROM shipping_customer
WHERE id IN (1, 4)
UNION
SELECT id, business_name, 'billing' AS type
FROM billing_customer
WHERE
id IN (1, 4) OR
id IN (SELECT billing_customer_id from shipping_customer WHERE id IN (1, 4))
他沒有子查詢就問。
碼:
SELECT id, business_name, 'shipping' AS type
FROM shipping_customer
WHERE id IN (1, 4)
UNION ALL
SELECT b.id AS [id],
b.business_name AS [business_name],
'billing' AS [type]
FROM shipping_customer s
JOIN billing_customer b
ON s.billing_customer_id = b.id
WHERE s.id IN ( 1, 4)
OR b.id IN ( 1, 4)
您能看到這是否正確嗎? 對於“想要的輸出就是每個客戶”的含義,我不清楚。 這也可能不是最優化的方法。
您可以UNION三套:
運送客戶加入到計費客戶
SELECT id,business_name,'shipping'AS類型,從shipping_customer WHERE id IN(1,4),UNION SELECT id,business_name,'billing',AS類型,FROM billing_customer WHERE id IN(1,4) ,類型為FROM shipping_customer sc INNER JOIN billing_customer bc on sc.billing_customer_id = bc.id,其中“通過運輸計費”在哪里sc.billing_customer_id IN(1,4)
問題中的查詢是一種很好的顯式方式,我唯一用EXISTS代替IN的方法是:
SELECT id, business_name, 'shipping' AS type
FROM shipping_customer
WHERE id IN (1, 4)
UNION
SELECT id, business_name, 'billing' AS type
FROM billing_customer bc
WHERE
id IN (1, 4) OR
EXISTS (SELECT 1 FROM shipping_customer
WHERE bc.id = billing_customer_id AND id IN (1, 4))
如果您使用的是SQL Server 2012+,則可以嘗試以下查詢:
SELECT IIF(customerType = 'sName', scId, bcId) AS id,
customer,
IIF (customerType = 'sName', 'shipping', 'billing') AS type
FROM (
SELECT sc.id AS scId, bc.id AS bcId,
sc.business_name AS sName, bc.business_name AS bName
FROM shipping_customer AS sc
INNER JOIN billing_customer AS bc ON sc.billing_customer_id = bc.id
) src
UNPIVOT (
customer FOR customerType IN (sName, bName)
) unpvt
WHERE (customerType = 'sName' AND (scId IN (1,4)))
OR ((customerType = 'bName') AND ((scId IN (1,4)) OR (bcId IN (1,4))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.