0

我的场景是货运公司。我有 Shipments、Senders、Recievers 和 Cities 表。Shipments 表包含 shipping_category、sender_id、reciever_id。Cities 表包含 ID 和 city_name。Sender 表保存 sender_id,sender_city 等于 city 表的 ID。Recievers 表包含reciever_id 和reciever_city,它们等于city 表的ID。

我设法显示属于类别 1 并且具有不同协调性的货物,并按城市的 ID 对它们进行计数,例如

From_City || 前往_城市 || 数数

1205 || 1346 || 7

我使用下面的代码:

SELECT  S.city AS From_City, R.city AS To_City , COUNT( * ) 
FROM Shipments Sh, Recievers R, Senders S
WHERE SH.category=1
AND SH.sender_id = S.ID
AND SH.reciever_id = R.ID
GROUP BY From_City, To_City
ORDER BY COUNT( * ) DESC 

我想要的是从城市表中按城市名称获取同一张表,如下所示:

From_City || 前往_城市 || 数数

巴黎 || 伦敦 || 7

注意:请不要建议更改数据库表。这只是表达我的情况的一个例子。

4

1 回答 1

1

试试这个:

SELECT
    `sender_cities`.`city_name` AS `From_City`,
    `receiver_cities`.`city_name` AS `To_City`,
    COUNT(*) as `Count`
FROM 
    `shipments` `ship`
    INNER JOIN `senders` `s` ON (`ship`.`sender_id` = `s`.`sender_city`)
    INNER JOIN `cities` `sender_cities` ON (`s`.`sender_city` = `sender_cities`.`city_id`)
    INNER JOIN `receivers` `r` ON (`ship`.`receiver_id` = `r`.`sender_city`)
    INNER JOIN `cities` `receiver_cities` ON (`r`.`receiver_city` = `receiver_cities`.`city_id`)
GROUP BY 
    `From_City`,
    `To_City`
ORDER BY 
    `Count` DESC
于 2013-07-18T22:15:32.547 回答