【发布时间】:2020-10-31 17:59:15
【问题描述】:
需要显示以下列(3)使用UNION返回:
- 所有没有发票的客户
- 所有未售出的产品
- 类别:这与“客户”或“产品”有关吗?打印“客户或产品”
- ID:Customer.id (category="customer") 或 product.id (category="product")
- 名称:customer.customer_name (category="customer") 或 product.product_name (category="product")
表格:
客户
- 身份证
- 客户名称
- city_id
- 客户地址
- contact_person
- 电子邮件
- 电话
产品
- 身份证
- sku
- 产品名称
- product_description
- 当前价格
- quantity_in_stock
发票
- 身份证
- invoice_number
- customer_id
- user_account_id
- total_price
- time_issued
- time_due
- time_paid
- time_canceled
- time_refunded
Invoice_Item
- 身份证
- invoice_id
- product_id
- 数量
- 价格
- line_total_price
目前有以下:
SELECT
category,
CASE
WHEN category = 'customer' THEN c.id
WHEN category = 'product' THEN p.id
END AS 'id',
CASE
WHEN category = 'customer' THEN c.customer_name
WHEN category = 'product' THEN p.product_name
END AS 'name'
FROM
(
SELECT
CASE
WHEN c.id = c.id THEN 'customer'
WHEN p.id = p.id THEN 'product'
END as 'category'
FROM
customer as c
LEFT Join -- Left join to show all customers even those with & without invoices
invoice as i
ON c.id = i.customer_id
AND i.id IS NULL -- Gives me all customers who do not have an invoice
JOIN invoice_item as ii
ON i.id = ii.invoice_id
Join product p
ON p.id = ii.product_id
) tb1
UNION ALL
SELECT
category,
CASE
WHEN category = 'customer' THEN c.id
WHEN category = 'product' THEN p.id
END AS 'id',
CASE
WHEN category = 'customer' THEN c.customer_name
WHEN category = 'product' THEN p.product_name
END AS 'name'
FROM
(
SELECT
CASE
WHEN c.id = c.id THEN 'customer'
WHEN p.id = p.id THEN 'product'
END as 'category'
FROM
product as p
LEFT JOIN -- Left join to show all products even those that sold and not sold
invoice_item as ii
ON p.id = ii.product_id
AND ii.invoice_id IS NULL -- Gives me products that didnt sell
JOIN invoice as i
ON ii.invoice_id = i.id
) tb2
欢迎任何建议,因为我一直在试图弄清楚如何将类别显示为“产品”或“客户”。提前致谢!
【问题讨论】: