mysql连接两个不同的表来列出一个结果

时间:2012-10-11 00:01:56

标签: mysql union

我有两个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变量中。因此,当我运行结果时,它看起来就像来自“发票”表。

如何确定每个特定行从哪个表中拉出来?

谢谢你, 安迪

2 个答案:

答案 0 :(得分: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,并按发票日期对其进行排序。

答案 1 :(得分: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'