mysql如何使用join和left join

时间:2019-02-15 03:47:40

标签: mysql

我想使用连接和左连接显示我的数据库。但看起来效果不佳。

这是我尝试的

SELECT ordercustline.QuantityOrdered,ordercustline.ProductID,ordercustline.UnitCustPrice,ordercustline.QuantityDelivered,ordercustline.Active,ordercustline.ProductNumber,products.ProductNumber as PN,products.id,pdt.ProductName,dbpjs.CodeName,ordercustline.id as oid, pdt.LanguageID 
  FROM ordercustline 
  LEFT JOIN products ON products.id = ordercustline.ProductID 
  LEFT JOIN producttexts as pdt ON pdt.ProductID = products.id 
  JOIN DiagnosisBPJS as dbpjs ON dbpjs.id = ordercustline.ProductNumber 
  WHERE ordercustline.OrderID = 20 AND ordercustline.Active = 2 AND pdt.LanguageID = 'en'

问题是,当ordercustline.ProductID具有null值时,查询将无法工作,我认为是因为pdt.LanguageID = 'en'

当我删除它时,查询工作正常,但是我想用pdt.LanguageID = 'en'过滤产品。

即使ordercustline.ProductID的值为null,我也必须做些什么才能使它工作。

1 个答案:

答案 0 :(得分:1)

pdt.LanguageID = 'en'的条件置于ONClausee而不是Where clause

SELECT ordercustline.QuantityOrdered,ordercustline.ProductID,ordercustline.UnitCustPrice,ordercustline.QuantityDelivered,ordercustline.Active,ordercustline.ProductNumber,products.ProductNumber as PN,products.id,pdt.ProductName,dbpjs.CodeName,ordercustline.id as oid, pdt.LanguageID 
  FROM ordercustline 
  LEFT JOIN products ON products.id = ordercustline.ProductID 
  LEFT JOIN producttexts as pdt ON pdt.ProductID = products.id AND pdt.LanguageID = 'en'
  JOIN DiagnosisBPJS as dbpjs ON dbpjs.id = ordercustline.ProductNumber 
  WHERE ordercustline.OrderID = 20 AND ordercustline.Active = 2