0

我有两个 MySQL 表:'invoice' 和 'credit_memo'

我想将它们结合起来并列出一个按日期排序的结果。

发票:
ID INT
日期 DATETIME
customer_id INT

credit_memo:
ID INT
日期 DATETIME
customer_id INT

我的最后尝试:

(SELECT ID AS invoice_number FROM invoice)
UNION
(SELECT ID AS credit_memo_number FROM credit_memo)
ORDER BY date

问题是 invoice_number 和 credit_memo_number 都被放入 invoice_number 变量中。因此,当我运行结果时,它看起来像是来自“发票”表。

如何确定每个特定行从哪个表中提取?

谢谢你,安迪

4

2 回答 2

0
select id, t.table_name from invoice join information_schema.tables t on t.table_name='invoice'
union
select id, t.table_name from credit_memo join information_schema.tables t on t.table_name='credit_memo'
于 2012-10-11T00:12:15.793 回答
0

以下是您将如何处理它。

这两个表都有客户 ID,因此我们可以通过它加入它们:

SELECT i.ID AS invoice_number,c.ID AS credit_memo_number 
FROM invoice i
JOIN credit_memo c ON c.customer_id = i.customer_id
ORDER BY i.date ASC

这将选择发票 ID 和信用 ID,并按发票日期排序。

于 2012-10-11T00:06:14.763 回答