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 | business_name | type |
+-------------+--------------------+----------+
| 1 | Soylent Corp | shipping |
| 3 | Acme Corporation | billing | <- 1 has billing_customer = 3
| 4 | Globex Corporation | billing |
+-------------+--------------------+----------+
有没有办法避免subselect?
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))
答案 0 :(得分:1)
他在没有子查询的情况下提出要求。
代码:
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)
你能看出这是否正确吗?我不明白你的意思是什么'通缉输出是每个客户'。这也可能不是最优化的方法。
答案 1 :(得分:0)
你可以使用UNION三套:
运送客户加入结算客户
SELECT id,business_name,&#39; shipping&#39; AS类型 来自shipping_customer 在哪里id IN(1,4) 联盟 SELECT id,business_name,&#39; billing&#39; AS类型 来自billing_customer 哪里 id IN(1,4) 联盟 SELECT sc.billing_customer_id, bc.business_name,&#39;通过运费结算&#39;作为类型 来自shipping_customer sc INNER JOIN billing_customer bc on sc.billing_customer_id = bc.id. WHERE 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))
答案 2 :(得分:0)
如果您使用的是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))))