如何在MySQL数据库中加入三个表?

时间:2015-05-10 08:45:10

标签: mysql sql

昨晚我和JOIN一起玩了两个表,这两个表工作得很好,但我需要生成一个CSV文件,所以需要来自三个不同表的数据,并想知道这是否正确?它需要通过发票编号将它们全部链接起来,在这种情况下是发票:

SQL:

SELECT * 
        FROM invoices i
        JOIN customers c
        JOIN invoice_items p
        ON c.invoice = i.invoice
        ON p.invoice = i.invoice
        WHERE i.invoice = c.invoice
        AND i.invoice = p.invoice
        ORDER BY i.invoice

1 个答案:

答案 0 :(得分:0)

将您的查询更改为

$query = "SELECT i.* 
         FROM invoices as i 
         JOIN customers as c ON c.invoice = i.invoice 
         JOIN invoice_items as p ON p.invoice = i.invoice 
         ORDER BY i.invoice";

而不是

$query = "SELECT * 
        FROM invoices i
        JOIN customers c
        JOIN invoice_items p
        ON c.invoice = i.invoice
        ON p.invoice = i.invoice
        WHERE i.invoice = c.invoice
        AND i.invoice = p.invoice
        ORDER BY i.invoice";

如果仅使用JOIN关键字,那么它将像INNER JOIN一样使用,否则您必须定义连接类型。示例:LEFT JOINRIGHT JOIN