MySQL查询,多个计数和总和

时间:2014-11-27 13:07:22

标签: mysql

我有一个MySQL查询输出到php表但我在加入两个使用COUNT的表时遇到问题:

$query = "SELECT mqe.registration, 
        COUNT(*) AS numberofenqs,
        COUNT(DISTINCT ucv.ip) AS unique_views,
        SUM(ucv.views) AS total_views
        FROM main_quick_enquiries AS mqe
        LEFT OUTER JOIN used_car_views AS ucv
        ON ucv.numberplate = mqe.registration
        WHERE mqe.registration IS NOT NULL
        GROUP BY mqe.registration ORDER BY numberofenqs DESC";

查询运行,但numberofenqs列中的数字总是错误的,因为我知道通过自己执行该查询它会得到正确的结果:

SELECT registration, COUNT(*) AS numberofenqs FROM main_quick_enquiries GROUP BY registration ORDER BY numberofenqs DESC

为什么COUNT(*)在最高查询代码中无法正常工作?从哪里获取数据?

2 个答案:

答案 0 :(得分:1)

可能是因为LEFT OUTER JOIN ......

尝试运行:

SELECT registration
, count(*)
FROM main_quick_enquiries
GROUP BY registration

并将其与此结果进行比较

SELECT mqe.registration
, count(*)
FROM main_quick_enquiries mqe
LEFT OUTER JOIN used_car_views ucv
ON ucv.numberplate = mqe.registration
GROUP BY mqe.registration

在双重行中可能存在问题:)尝试找到一个特定的注册号,并比较两个查询的详细信息

SELECT *
FROM main_quick_enquiries
WHERE registration = XXXX

+

SELECT *
FROM main_quick_enquiries mqe
LEFT OUTER JOIN used_car_views ucv
ON ucv.numberplate = mqe.registration
WHERE registration = XXXX

你应该看到差异

答案 1 :(得分:0)

全部感谢,但我想我已经用COUNT(DISTINCT mqe.id)而不是COUNT(*)来钉它。