我有两个表tblFuneralHomes
和tblFuneralTransactions
。一个表可能有许多事务。我需要返回用户的funeralHomes
并计算交易次数,但是如果funeralHomes没有交易,则不会返回结果。
Select tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key, count(tft.id) as counts from tblFuneralHomes tfh
inner join tblFuneralTransactions tft on tft.funeral_home_guid = tfh.funeral_home_guid where (tft.canceled=0 and tft.completed=0)
and tfh.funeral_home_guid in (select funeral_home_guid
from tblDirectorHomes
where director_id = '1789a3ae-95e5-4719-ac09-bd1ada01dd5b')
group by tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key
我知道当前有3个funeralHomes
用户。
但是当我加入交易并计算在内时,其中一个房屋没有交易,也没有显示。
答案 0 :(得分:3)
您必须使用LEFT JOIN
而不是INNER JOIN
,以便获取tblFuneralHomes
的所有记录:
SELECT tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key, COUNT(tft.id) AS counts
FROM tblFuneralHomes tfh LEFT JOIN tblFuneralTransactions tft ON tft.funeral_home_guid = tfh.funeral_home_guid
WHERE (tft.funeral_home_guid IS NULL OR (tft.canceled = 0 AND tft.completed = 0))
AND tfh.funeral_home_guid IN (
SELECT funeral_home_guid
FROM tblDirectorHomes
WHERE director_id = '1789a3ae-95e5-4719-ac09-bd1ada01dd5b'
)
GROUP BY tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key
您在tblFuneralTransactions
条件下使用WHERE
列。如果tblFuneralHomes
的记录没有tblFuneralTransactions
,则tblFuneralTransactions
记录的所有列值都是NULL
。因此,以下条件为假:tft.canceled = 0 AND tft.completed = 0
。
要包括tblFuneralHomes
的所有记录,您需要允许tblFuneralTransactions
的列为NULL
。所以您必须替换此条件
(tft.canceled = 0 AND tft.completed = 0)
到以下
(tft.funeral_home_guid IS NULL OR (tft.canceled = 0 AND tft.completed = 0))
答案 1 :(得分:2)
我建议以下查询(对查询的少量修改):
Select tfh.funeral_home_guid,
tfh.funeral_home_name,
tfh.reference_key,
sum(case when tft.id is null then 0 else 1 end) as counts
from tblFuneralHomes tfh
left join tblFuneralTransactions tft on tft.funeral_home_guid = tfh.funeral_home_guid
where (tft.canceled=0 and tft.completed=0)
and tfh.funeral_home_guid in (select funeral_home_guid
from tblDirectorHomes
where director_id = '1789a3ae-95e5-4719-ac09-bd1ada01dd5b')
group by tfh.funeral_home_guid, tfh.funeral_home_name, tfh.reference_key
我切换到left join
,因此不匹配的fun仪馆仍将包含在结果集中。此外,我还处理了其他表中的nul
值:当它为null时,列应为0,否则应为1。然后足以对这些值求和。