MySQL查询计数和加入

时间:2016-03-04 17:17:52

标签: mysql sql join count

我有以下查询:

SELECT shipments.file_number, file_creation_date, city_name, container_sequence
FROM cities, countries, shipments
LEFT OUTER JOIN container_details ON shipments.file_number = container_details.file_number
WHERE
destination_ocean_port = city_code
AND cities.country_code = countries.country_code
AND cities.country_code = 'CN'
AND file_creation_date > '2015-1-1'
AND file_creation_date < '2016-1-1' 

ORDER BY shipments.file_number;

它会像这样返回:

enter image description here

正如您在某些情况下所看到的,每个file_number有多个container_sequences。我怎样才能得到它所以它只返回每个file_number中的一个,同时显示每个file_number有多少个container_sequences的计数?

我知道它可能与连接和count()有关,但我无法弄明白。

由于

2 个答案:

答案 0 :(得分:1)

您需要按功能和分组依据使用count()组来获得所需的输出。我还重写了连接以使用内部连接和显式连接语法。

SELECT shipments.file_number, file_creation_date, city_name, count(container_sequence) as number_of_containers
FROM cities 
INNER JOIN countries ON cities.country_code = countries.country_code
INNER JOIN shipments ON shipments.destination_ocean_port = cities.city_code
LEFT OUTER JOIN container_details ON shipments.file_number = container_details.file_number
WHERE 
    cities.country_code = 'CN'
AND file_creation_date > '2015-1-1'
AND file_creation_date < '2016-1-1' 
GROUP BY shipments.file_number, file_creation_date, city_name
ORDER BY shipments.file_number;

答案 1 :(得分:-1)

SELECT shipments.file_number, file_creation_date, city_name, count(container_sequence) as total_container_sequence
FROM cities, countries, shipments
LEFT OUTER JOIN container_details ON shipments.file_number = container_details.file_number
WHERE
destination_ocean_port = city_code
AND cities.country_code = countries.country_code
AND cities.country_code = 'CN'
AND file_creation_date > '2015-1-1'
AND file_creation_date < '2016-1-1' 
GROUP BY shipments.file_number
ORDER BY shipments.file_number;