我正在尝试编写一个查询,如果产品有任何产品信息和照片,
select
prod.pID, prod.Manufacturer_Name, prod.pUPC, prod.pNum, prod.pPrice, prod.pSalesPrice, prod.pSalesDate, prod.pSalesEndDate, prod.pSale,
GROUP_CONCAT(photoName) as photos
from
ds_products as prod
inner join ds_photos as pics on pics.objectID=prod.pID
where
pics.photoFlag =2
group by
prod.pID
问题在于,没有照片的产品会被排除在结果集之外。我需要添加和/或更改哪些内容才能让照片表中未显示的产品显示在结果中?
由于
修改的
我尝试了LEFT JOIN而不是inner,但得到了相同的结果集。如果我只是运行:
select
prod.pID, prod.Manufacturer_Name, prod.pUPC, prod.pNum, prod.pPrice, prod.pSalesPrice, prod.pSalesDate, prod.pSalesEndDate, prod.pSale
from
ds_products as prod
我得到大约600k的结果。内部和/或左连接查询获得大约190k的结果。还有另一种方法吗?
答案 0 :(得分:2)
使用外部联接
select
prod.pID, prod.Manufacturer_Name, prod.pUPC, prod.pNum, prod.pPrice, prod.pSalesPrice, prod.pSalesDate, prod.pSalesEndDate, prod.pSale,
GROUP_CONCAT(photoName) as photos
from
ds_products as prod
LEFT join ds_photos as pics on pics.objectID=prod.pID
where
pics.photoFlag =2 OR pics.photoFlag is NULL
group by
prod.pID
我添加了一个条件,检查photoFlag对于没有相应图片的产品是否为空 这是工作小提琴:http://sqlfiddle.com/#!2/c2a9c/1/0
有关详细信息:http://dev.mysql.com/doc/refman/5.0/en/outer-join-simplification.html
答案 1 :(得分:0)
你需要像这样使用LEFT JOIN而不是INNER JOIN
select
prod.pID, prod.Manufacturer_Name, prod.pUPC, prod.pNum, prod.pPrice, prod.pSalesPrice, prod.pSalesDate, prod.pSalesEndDate, prod.pSale,
GROUP_CONCAT(photoName) as photos
from
ds_products as prod
LEFT JOIN ds_photos as pics on pics.objectID=prod.pID
group by
prod.pID
注意我还删除了你的where子句,因为这是在pics表中寻找一个会限制结果集的值。