我有一个零件表和一个价格表 零件表是指与保修零件号相关的自身。
我想运行查询以显示所有零件,如果它们有保修,则显示保修的零件号,然后显示价格。
select `P`.`partNumber` AS `partNumber`,`P`.`Description` AS `Description`,`PP`.`Price` AS `Price`,`P`.`WarrantyPartNumber` AS `WarrantyPartNumber`,`W`.`Description` AS `WDescription`
from ((`tblPart` `P` left outer join `tblPart` `W` on `P`.`WarrantyPartNumber` = `W`.`partNumber`) inner join `tblPartPrice` `PP` on `P`.`partNumber` = `PP`.`partNumber`)
where PP.tierID = 0
以上给出正确的输出,但没有价格。添加“保修价格清单”参考后,我只会得到显示保修的零件。
select `P`.`partNumber` AS `partNumber`,`P`.`Description` AS `Description`,`PP`.`Price` AS `Price`,`P`.`WarrantyPartNumber` AS `WarrantyPartNumber`,`W`.`Description` AS `WDescription`, `wPP`.`Price` AS `wPrice`
from ((`tblPart` `P` left outer join `tblPart` `W` on `P`.`WarrantyPartNumber` = `W`.`partNumber`) inner join `tblPartPrice` `PP` on `P`.`partNumber` = `PP`.`partNumber`) right outer join `tblPartPrice` `wPP` on `W`.`partNumber` = `wPP`.`partNumber`
where PP.tierID = 0 AND wPP.tierID = 0
预期结果
所有带或不带保修的零件均显示任何保修费用 元素(如果存在)。
答案 0 :(得分:0)
这是您的查询,已被固定为至少可读:
select p.partNumber, p.Description, pp.Price,
pp.WarrantyPartNumber,
w.Description AS WDescription, wPP.Price AS wPrice
from tblPart p left outer join
tblPart w
on p.WarrantyPartNumber = w.partNumber inner join
tblPartPrice pp
on p.partNumber = pp.partNumber right outer join
tblPartPrice wPP
on w.partNumber = wPP.partNumber
where PP.tierID = 0 AND wPP.tierID = 0;
使用where
子句混合左右联接非常复杂。您的查询似乎可以使用更简单的方法。
如果我理解正确,则保修部件的等级必须相同。因此,此条件应位于on
子句中:
select p.partNumber, p.Description, pp.Price,
pp.WarrantyPartNumber,
w.Description AS WDescription, wPP.Price AS wPrice
from tblPart p join
tblPartPrice pp
on p.partNumber = pp.partNumber left outer join
tblPart w
on p.WarrantyPartNumber = w.partNumber left join
tblPartPrice wpp
on w.partNumber = wpp.partNumber and
wpp.tierID = pp.TierId
where pp.tierID = 0;
请注意join
:
p
内部联接 pp
,因为它们应该匹配。您期望每个零件的价格。w
,因为可能没有保修部分wpp
,因为前一个left join
可能找不到匹配的行。