我试图使用左连接获取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
答案 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'