查询具有对同一表的多个引用

时间:2013-10-10 00:53:47

标签: mysql sql

我有2张桌子。一个有联系信息,另一个有城市ID和名字。实施例。

Table 1 Contacts
ID,Name, HomeCity, BusinessCity
123,Ben,1,2

Table 2 Cities
CityID, CityName
1 Austin
2 Boston

我想创建一个简单的查询,显示Ben的家乡城市和商业城市。

我不明白如何包含两次引用CityName的查询。

到目前为止我只有:

SELECT Contacts.Name, Contacts.HomeCity, Contacts.BusinessCity, Cities.CityName
FROM Contacts,Cities
WHERE Contacts.ID=123 AND Contacts.HomeCity=Cities.CityID

我只是不明白。我希望查询向我展示的是:

Name, Home City, Business City
Ben, Austin, Boston

2 个答案:

答案 0 :(得分:2)

语法可能不完美,但这个一般概念应该有效:

SELECT 
    Contacts.Name, 
    (SELECT CityName FROM Cities WHERE Contacts.HomeCity=Cities.CityID) AS HomeCity, 
    (SELECT CityName FROM Cities WHERE Contacts.BusinessCity=Cities.CityID) AS BusinessCity
FROM Contacts WHERE Contacts.ID=123

答案 1 :(得分:2)

您可以多次将联系人表格加入城市表格:

SELECT contacts.name, 
    cities.CityName 'Home City', 
    cities2.CityName 'Business City'
FROM contacts
    JOIN cities ON contacts.homecity = cities.cityid
    JOIN cities cities2 ON contacts.businesscity = cities2.cityid
WHERE contacts.ID=123

根据您的预期结果,您可能需要使用OUTER JOINs - 有关其他信息,请参阅以下链接。