简体   繁体   中英

MySQL Query, multiple counts and sums

I have a MySQL query that outputs to a php table but I'm having issues in joining two tables that both use a 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";

The query runs, but the number within the numberofenqs column is always wrong as i know from performing that query on its own that it comes in with the correct result:

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

Why is the COUNT(*) not working correctly in top query code and where is it getting the figures from?

it could be because of LEFT OUTER JOIN ...

Try to run this:

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

and compare it with this result

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

There could be a problem :) in duplicity rows... try to find one specific registration number, and compare the details of both query

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

you should see the diffs

谢谢大家,但我想我用COUNT(DISTINCT mqe.id)代替了COUNT(*)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM