Mysql查询在左连接中返回错误的结果

时间:2016-03-01 10:55:00

标签: php mysql codeigniter

我正在使用Codeigniter和MySQL。我有两个表名为informationreview

此处我附上了information表的图片截图。

enter image description here

这是我的review

enter image description here

这是我的info_img

enter image description here

现在,根据review,我希望按information id获得mytable的总数。

在这里,我写了这样的查询:

SELECT 
    info.*,
    info_img.name AS image,
    COUNT(rev.review_id) AS total
FROM
    information AS info
        LEFT JOIN
    info_img ON info.information_id = info_img.information_id
        LEFT JOIN
    review AS rev ON rev.information_id = info.information_id
WHERE
    info.status = 1
        AND FIND_IN_SET('3', info.category)
GROUP BY rev.information_id
ORDER BY info.information_id ASC
LIMIT 0 , 3

我对information_id = 8的18次审核计数错了。而不是它,我希望information_id = 8的评论数为6。

1 个答案:

答案 0 :(得分:2)

我认为你所要做的就是为你的计数增添不同......:

select info.*,info_img.name as image,count(distinct rev.review_id) as total
from information as info
 left join info_img
   ON info.information_id = info_img.information_id 
 left join review as rev
   ON rev.information_id = info.information_id 
WHERE info.status =1
      AND FIND_IN_SET('3', info.category)
GROUP BY rev.information_id 
order by info.information_id Asc
LIMIT 0,3

它发生的原因可能是因为信息表正在将结果相乘(看起来是3)所以每个review_id将被计算3次,因此 - 计算不同