即使外键为null,如何获取结果集?

时间:2013-09-17 14:56:45

标签: mysql sql null key

我正在使用以下查询来获取发票明细。因此,即使没有客户注册发票,我也需要获取发票明细。因此,在这种情况下,发票表中的外键cusidfk为空。那么我怎样才能得到结果集?如何在同一结果集中为客户显示null?

SELECT invoice.invno,invoice.invdate,invoice.invtime,customer.bizname,invoice.addedby,item.nameinsin,invoicedetails.price,invoicedetails.soldprice,invoicedetails.qty,invoicedetails.subtotal,invoicedetails.total,payment.pamt,invoice.tot
FROM invoice, invoicedetails, item, customer, payment
WHERE invoice.invno=invoicedetails.invnofk
  AND invoicedetails.itemfkcode=item.itemcode
  AND customer.cusid=invoice.cusidfk
  AND invoicedetails.invnofk='0000000000005'
  AND invoice.invno=payment.invfkno

1 个答案:

答案 0 :(得分:3)

我建议使用JOINLEFT JOIN而非隐式加入。

SELECT ...
FROM invoice
JOIN invoicedetails ON invoice.invno = invoicedetails.invnofk
JOIN item ON invoicedetails.itemfkcode = item.itemcode
JOIN payment ON invoice.invno = payment.invfkno
LEFT JOIN customer ON customer.cusid = invoice.cusidfk
WHERE invoicedetails.invnofk = '0000000000005'

如果没有条目,则LEFT JOIN所有customer字段都为NULL