我有这个问题:
SELECT bussiness.bussId , count(favourites.userID) as fav
from `bussiness`
LEFT JOIN `favourites` on (`bussiness`.`bussId` = `favourites`.`bussId`)
where bussiness.bussId= 12310
当我运行此查询时,我得到fav = 2.
但当我离开加入另一张桌子时,
SELECT bussiness.bussId , count(favourites.userID) as fav from `bussiness`
LEFT JOIN `favourites` on (`bussiness`.`bussId` = `favourites`.`bussId`)
LEFT JOIN `invoices` on (`bussiness`.`bussId` = `invoices`.`bussId`)
where bussiness.bussId= 12310
我得到的是fav = 88而不是2
为什么会这样?
答案 0 :(得分:0)
似乎hello表中出现多次bussId导致返回的行数相乘。由于您没有对userID进行明确计数,因此查询只是计算包含userID的行数。如果要计算唯一身份用户的数量,则需要使用COUNT DISTINCT
。像这样:
SELECT bussiness.bussId , count(distinct favourites.userID) as fav from `bussiness`
LEFT JOIN `favourites` on (`bussiness`.`bussId` = `favourites`.`bussId`)
LEFT JOIN `hello` on (`bussiness`.`bussId` = `hello`.`bussId`)
where bussiness.bussId= 12310