2

我有一点有线问题。
我必须从查询 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
4

2 回答 2

6

试试SELECT COUNT(DISTINCT tl.ItemLikeId) AS a, COUNT(DISTINCT tib.PacketId) as b

您的联接为您提供十行,因此每个表都有十个 ID。但是,并非所有 ID 都是唯一的。您正在寻找唯一的 ID。

于 2012-11-30T19:41:30.873 回答
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

另一种方法,如果你正在使用ItemLikesItemsInPackets只是计数

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
于 2012-11-30T19:43:51.987 回答