MySQL查询帮助 - 仅显示可用的城市

时间:2015-11-15 21:38:04

标签: php mysql sql

我在MySQL中拥有CitiesCountriesCustomers个表。

Cities: city_id, city_name, ...
Counties: county_id, city_id, county_name, ...
Customers: cus_id, city_id, county_id, ...

而不是在Country中列出所有城市(以及城市下的县) - 我只想列出CitiesCustomers已注册的县。

这里有MySQL专家来帮助我吗?谢谢。 问候。

2 个答案:

答案 0 :(得分:1)

您的表格Customers未正确规范化。您不应该在此表中添加列city_id,因为county_id => city_id(给定county_id您可以找到city_id)。

我不确定我是否正确理解了您(如果没有请更好地解释提供样本数据)但是您想要的是我认为您可以使用以下查询:

SELECT aa.city_name, bb.county_name
FROM Cities AS aa
INNER JOIN Counties AS bb
ON aa.city_id = bb.city_id
INNER JOIN Customers AS cc
ON bb.county_id = cc.county_id;

答案 1 :(得分:0)

Select UNIQUE city_id from Customers
JOIN Cities 
ON Customers.city_id=Cities.city_id;

我在那里解释,但我希望证明我的观点。