我有一点连线问题
我必须从查询Likes和Collects中选择两个计数,但当我添加第二个查询而不是2 likes and 10 collects
时,我得到10 likes and 10 collects
。
我在这里做错了什么?
select COUNT(tl.ItemLikeId) as a, COUNT(tib.PacketId) as b
from Items i
left join ItemLikes il
on il.ItemId = i.ItemId
left join ItemsInPackets iip
on iip.ItemId = i.ItemId
where i.ItemId = 14591
答案 0 :(得分:6)
尝试SELECT COUNT(DISTINCT tl.ItemLikeId) AS a, COUNT(DISTINCT tib.PacketId) as b
。
您的联接会为您提供十行,因此每个表中都有十个ID。但是,并非所有ID都是唯一的。您正在寻找唯一的ID。
答案 1 :(得分:2)
Count返回行数。不是具有值的行数,而不是不同行的数量。
获取具有值
的数字行行select SUM(CASE WHEN tl.ItemLikeId IS NOT NULL THEN 1 ELSE 0 END) as a,
SUM(CASE WHEN tib.PacketId IS NOT NULL THEN 1 ELSE 0 END) as b
要获取不同值的数量,请执行zimdanen建议并使用COUNT(DISTINCT)
select COUNT(DISTINCT tl.ItemLikeId) as a, COUNT(DISTINCT tib.PacketId) as b
另一种方法,如果您使用的是ItemLikes
和ItemsInPackets
,则为计数
select
(
SELECT COUNT(ItemLikeId)
FROM ItemLikes
WHERE ItemId = i.ItemId
) as a,
(
SELECT COUNT(PacketId)
FROM ItemsInPackets
WHERE ItemId = i.ItemId
) as b
from Items i
where i.ItemId = 14591