从3个表中检索数据,其中1个表可能不包含值,第3个表的“where”条件

时间:2017-03-14 13:49:42

标签: mysql

我试图使用左连接获取3个表数据。表名是tblOffer,tblCompanyDetails和tblFavourite。

SELECT tblOffer.OID, tblOffer.OfferCategory, 
    tblOffer.OfferTitle,tblOffer.OfferDetails, 
    tblOffer.ProductImagePath,
    tblOffer.IsExciting,
    tblOffer.ExpiringDate, 
    tblCompanyDetails . *,
    tblFavourite.IsFavourite 
FROM tblOffer 
    LEFT JOIN tblCompanyDetails ON tblOffer.CID = tblCompanyDetails.CID 
    LEFT JOIN tblFavourite ON tblOffer.OID = tblFavourite.OID 
WHERE tblOffer.OfferCategory = 'shopping'

tblFavourite中不存在任何行。所以tblFavourite.IsFavourite值为null。

我还有一个条件来从tblFavourite获取数据。

SELECT tblOffer.OID, 
    tblOffer.OfferCategory, 
    tblOffer.OfferTitle, 
    tblOffer.OfferDetails, 
    tblOffer.ProductImagePath, 
    tblOffer.IsExciting,
    tblOffer.ExpiringDate, 
    tblCompanyDetails . *,
    tblFavourite.IsFavourite 
FROM tblOffer 
    LEFT JOIN tblCompanyDetails ON tblOffer.CID = tblCompanyDetails.CID 
    LEFT JOIN tblFavourite ON tblOffer.OID = tblFavourite.OID 
WHERE tblOffer.OfferCategory = 'shopping' 
    AND tblFavourite.UID = 1

请注意我写的条件.. tblFavourite.UID = 1结尾。我知道条件错了。

如果没有行,我怎么能得到这三个表和tblFavourite.IsFavourite = 0

2 个答案:

答案 0 :(得分:0)

将条件放在左连接中的可选数据上,因此如果不满足此条件,它将不会过滤掉结果:

SELECT tblOffer.OID, 
tblOffer.OfferCategory, 
tblOffer.OfferTitle, 
tblOffer.OfferDetails, 
tblOffer.ProductImagePath, 
tblOffer.IsExciting,
tblOffer.ExpiringDate, 
tblCompanyDetails . *,
tblFavourite.IsFavourite 
FROM tblOffer 
LEFT JOIN tblCompanyDetails ON tblOffer.CID = tblCompanyDetails.CID 
LEFT JOIN tblFavourite on tblOffer.OID=tblFavourite.OID and tblFavourite.UID=1
where tblOffer.OfferCategory='shopping'

答案 1 :(得分:0)

tblFavourite.UID=1放入WHERE子句中,您已有效地将LEFT JOIN上的tblFavourite转换为INNER JOIN。如果将该条件移动到ON子句而不是WHERE子句中,那么即使tblOffer中没有匹配的行,您仍会从主表(tblFavourites)获取行。 1}}。

至于NULL替换0 tblFavourite.IsFavourite,您可以使用COALESCE()函数执行此操作。

这样的事情对你有用:

SELECT tblOffer.OID,
       tblOffer.OfferCategory,
       tblOffer.OfferTitle,
       tblOffer.OfferDetails,
       tblOffer.ProductImagePath,
       tblOffer.IsExciting,
       tblOffer.ExpiringDate,
       tblCompanyDetails.*,
       COALESCE(tblFavourite.IsFavourite,0)
FROM tblOffer
LEFT JOIN tblCompanyDetails ON tblOffer.CID = tblCompanyDetails.CID
LEFT JOIN tblFavourite ON tblOffer.OID=tblFavourite.OID AND tblFavourite.UID=1
WHERE tblOffer.OfferCategory='shopping'