需要将MySql查询加入3个表

时间:2014-10-27 03:12:55

标签: mysql sql join

SELECT products.acctnum,products.subacctnum,NOW(),
    items.amount,items.id,items.invoice_id,items.product_id,
    items.po_id, invoices.customer_id, purchaseorders.vendor_id FROM items
    INNER JOIN (products, invoices, purchaseorders)
            ON (items.product_id=products.product_id AND items.invoice_id=invoices.id
    AND items.po_id=purchaseorders.id)

这不返回......但是..

SELECT products.acctnum,products.subacctnum,NOW(),
    items.amount,items.id,items.invoice_id,items.product_id,
    items.po_id, purchaseorders.vendor_id FROM items
    INNER JOIN (products, purchaseorders)
            ON (products.product_id=items.product_id AND purchaseorders.id=items.po_id)

作品...

SELECT products.acctnum,products.subacctnum,NOW(),
    items.amount,items.id,items.invoice_id,items.product_id,
    items.po_id, invoices.customer_id FROM items
    INNER JOIN (products, invoices)
            ON (products.product_id=items.product_id AND invoices.id=items.invoice_id)

作品...

适用于结果中我需要的行,但是当我加入第3个表时,它不起作用。 LEFT JOIN显示了我需要的所有列,但有些行为NULL。

1 个答案:

答案 0 :(得分:0)

我想你想要的join子句看起来更像是这样:

FROM items LEFT JOIN
     invoices
     ON invoices.id = items.invoice_id LEFT JOIN
     purchaseorders
     ON purchaseorders.id = items.po_id LEFT JOIN
     products
     ON products.product_id = items.product_id

我不确定哪些字段在您选择时无效,但您可以通过coalesce()使用invoicespurchaseorders中的相应字段来解决此类问题。