I need count rows in tbl_L grouped by source and associated for single source the field flags (of the tbl_N) and the field COUNTRY_CODE (of the tbl_ip) and I tried this join query;
mysql> SELECT
a.source,
CA.source,
CB.COUNTRY_CODE2,
CB.FLAGS,
COUNT(*)
FROM
tbl_L A
JOIN tbl_N CA ON a.source = CA.source
JOIN tbl_ip CB ON UCASE(CA.source) = CB.COUNTRY_CODE2
WHERE
a.source NOT IN ('1X', '2F', '3T')
GROUP BY
a.source
LIMIT 5;
+---------+---------+---------------+--------+----------+
| source | source1 | COUNTRY_CODE2 | FLAGS | COUNT(*) |
+---------+---------+---------------+--------+----------+
| AD | AD | AD | AD.PNG | 10 |
| AL | AL | AL | AL.PNG | 46 |
| AR | AR | AR | AR.PNG | 6435 |
| AT | AT | AT | AT.PNG | 6528 |
| AU | AU | AU | AU.PNG | 2532 |
+---------+---------+---------------+--------+----------+
5 rows in set
This output is incorrect because if I tried this simple query count I have the exact numbers, can you help me?
thank you.
mysql> SELECT
source,
COUNT(*)
FROM
tbl_L
WHERE
source NOT IN ('1X', '2F', '3T')
GROUP BY
source
LIMIT 5;
+---------+----------+
| source | COUNT(*) |
+---------+----------+
| AD | 1 |
| AL | 1 |
| AR | 11 |
| AT | 4 |
| AU | 1 |
+---------+----------+
5 rows in set
No. The count is performed on the resulting table from the joins. With source ‘AD’ you have 1 x 1 x 10 = 10 rows, so the count returns 10.
But if there would’ve been 2 ‘AD’ rows in the second table, then the count would have returned 1 x 2 x 10 = 20.
If you need to count the number of rows with source = ‘AD’ in the first table, then you’ll have to use a subquery. Something like (it still won’t give you what you want, but it resolves the count problem ):
SELECT
a.source
, CA.source
, CB.COUNTRY_CODE2
, CB.FLAGS
, a.total
FROM
(SELECT
source
, COUNT(*) AS total
FROM tbl_L A
GROUP BY source
) AS a
INNER JOIN tbl_N CA
ON a.source = CA.source
INNER JOIN tbl_ip CB
ON UCASE(CA.source) = CB.COUNTRY_CODE2
WHERE a.source NOT IN ('1X', '2F', '3T')
LIMIT 5
By the way, I don’t understand why you need the the second table in that join? You don’t select anything from it, and you can link the first and third table directly.
Excellent guido2004. thanks a lot!
Small correction of details in the syntax GROU BY
SELECT
a.source
, CA.source
, CA.source_full_name
, CB.COUNTRY_CODE2
, CB.FLAGS
, a.total
FROM
(SELECT
source
, COUNT(*) AS total
FROM tbl_L A
GROUP BY source
) AS a
INNER JOIN tbl_N CA
ON a.source = CA.source
INNER JOIN tbl_ip CB
ON UCASE(CA.source) = CB.COUNTRY_CODE2
WHERE a.source NOT IN ('1X', '2F', '3T')
GROUP BY
a.source
ORDER BY
total DESC;
Affected rows: 0
Time: 1.969ms
By the way, I don’t understand why you need the the second table in that join? You don’t select anything from it, and you can link the first and third table directly.
Because in the table tbl_N I have full name of source, e.g.: source = US, full name = United States of America