编写复杂的SQL查询以在给定条件下加入另外五个表?

时间:2018-03-31 07:59:34

标签: sql join database-design

这是我的桌子设计:

enter image description here

我将查询写入这样的单独的DrugPackage表,它工作正常并给我16条记录。

Select  
    packText, ifnPriceAup
from 
    med.DrugPackage 
where 
    latest = '1' and available = '1' and baseDrug = '5102';

但我需要采取相关的BaseDrug table-> name以及Drug table-> name以及TradName table - >也是。我尝试了很多时间使用表连接,但我没有成功。

我写的像这个查询,但看起来不正确。

Select 
    brandedDrug.tradeName, basebrandedDrug.name, basebrandedDrug.id, 
    baseDrug.name, packText, ifnPriceAup 
from 
    med.DrugPackage  
left join 
    med.BaseDrug as baseDrug on med.DrugPackage.baseDrug = baseDrug.id  
left join 
    med.BaseBrandedDrug as basebrandedDrug on med.DrugPackage.brandedDrug = basebrandedDrug.id
left join 
    med.BrandedDrug as brandedDrug on  med.DrugPackage.baseDrug = brandedDrug.id 
where 
    med.DrugPackage.latest = '1' 
    and available = '1' 
    and baseDrug = '5102';

输出:

enter image description here

最后三列记录正确但前两位不正确。而且,我想打印商品名而不是ID。

1 个答案:

答案 0 :(得分:1)

试试这个。

使用join时,使用相同的数据类型和相关列进行连接

Select brandedDrug.tradeName ,basebrandedDrug.name,
basebrandedDrug.id, baseDrug.name , packText, ifnPriceAup 
from med.DrugPackage  
left join med.BaseDrug as baseDrug on med.DrugPackage.id = baseDrug.id  
left join med.BaseBrandedDrug as basebrandedDrug 
on med.DrugPackage.id = basebrandedDrug.id
left join med.BrandedDrug as brandedDrug 
on  med.DrugPackage.id = brandedDrug.nplid 
 where med.DrugPackage.latest = '1' 
and available ='1' and baseDrug ='5102';