1

我希望 tablecities中的 area_id 由它们的 area-name 右连接,这是 table 中的 name_en areas(I-强调行)。

表 1:城市

╔════════════╦═════════╦═══════════════╗
║ COUNTRY_ID ║ AREA_ID ║    NAME_EN    ║
╠════════════╬═════════╬═══════════════╣
║ US         ║       1 ║ Los Angeles   ║
║ US         ║       1 ║ San Francisco ║
║ US         ║       2 ║ Kansas City   ║
╚════════════╩═════════╩═══════════════╝

表 2:领域

╔════╦════════════╗
║ ID ║  NAME_EN   ║
╠════╬════════════╣
║  1 ║ California ║
║  2 ║ Missouri   ║
╚════╩════════════╝

我的查询:

SELECT c.country_id, c.area_id, c.name_en 
FROM `cities` AS c RIGHT JOIN `areas` AS a ON c.area_id = a.name_en 
4

3 回答 3

2

您不需要RIGHT JOIN这里,而是INNER JOIN.

SELECT  a.Country_ID, 
        a.Name_en CountryName,
        b.Name_en AreasName
FROM    Cities a
        INNER JOIN Areas b
            ON a.area_ID = b.ID

要进一步了解有关联接的更多信息,请访问以下链接:

输出

╔════════════╦═══════════════╦════════════╗
║ COUNTRY_ID ║  COUNTRYNAME  ║ AREASNAME  ║
╠════════════╬═══════════════╬════════════╣
║ US         ║ Los Angeles   ║ California ║
║ US         ║ San Francisco ║ California ║
║ US         ║ Kansas City   ║ Missouri   ║
╚════════════╩═══════════════╩════════════╝
于 2013-03-14T09:01:29.907 回答
2

查询应该是

   SELECT c.country_id, c.area_id, c.name_en 
   FROM cities AS c RIGHT JOIN areas AS a ON c.area_id = a.id 
于 2013-03-14T09:01:47.947 回答
2

首先你必须遵守规则,你不等于两个完全不同类型的字段。所以你不应该让他们平等。它们是不同的类型。另一方面,不建议使用右连接。你应该使用左连接,除了它。

SELECT a.country_id, a.name_en AS country_nameCountryName, b.name_en AS area_name FROM areas b LEFT JOIN cities a ON b.id = a.area_id

于 2013-03-14T09:08:53.267 回答