【问题标题】:How to join three tables together in MySQL?如何在 MySQL 中将三个表连接在一起?
【发布时间】:2016-05-16 09:06:18
【问题描述】:

我有一个存储国家、省和城市的表格位置。 我想通过 id 搜索一个城市;我也可以看到它的省和国家!我尝试了太多,但我真的不知道我需要写什么确切的查询。

我的表名是位置,这些是我的字段示例数据:

id             enName         localName   type     in_location
1              Iran              ایران    country          0
2              Fars             فارس      province         1
3              shiraz         شیراز       city             2
4              marvdasht        مرو دشت    city            2

我想在搜索 id = 3 时得到这个结果:

国家/省/市

伊朗/法尔斯/设拉子

如何编写此查询?我知道我必须加入表 3 次,但不知道具体怎么做。

我试过的代码:

SELECT 
    in_location ,
    enName 
FROM 
    location 
WHERE 
    id = 12321 as a
INNER JOIN
    SELECT 
        * 
    FROM 
        `fzxit_location` as b 
    on a.in_location = b.id

【问题讨论】:

  • Mysql 没有做分层查询的功能。但是,如果层次结构级别是预定义的,则可以实现此目的。一种更简单的方法是在 PHP 上编写一个递归函数来实现您正在尝试的功能。
  • 您的查询违背了关系数据库的目的,同一个表中的行不应该直接相关。
  • 你为什么要内联同一张表?

标签: php mysql sql join


【解决方案1】:

WHERE 语句应始终放在最后。我想这就是你要找的。不过,您将无法与 3 个或更少的孩子建立关系。

SELECT a.enName, b.enName, c.enName FROM location as a
LEFT JOIN location as b ON a.in_location = b.id
LEFT JOIN location as c ON b.in_location = c.id
WHERE a.id = 3

【讨论】:

  • 你快了 30 秒 :)
【解决方案2】:

虽然你没有指定其他表名,你可以试试这个..

select a.countryName, 
       b.proviceName, 
       c.cityName 
from ((country a 
         left join province b on a.countryId = b.countryId) 
         left join city c on a.countryId = c.countryId) 
where id = 3;  

【讨论】:

    【解决方案3】:

    此查询可能对您有所帮助!

    select from p.province_name,
                ct.country_name,
                c.city_name 
    from city as c 
       INNER JOIN provinces as p ON c.province_id=p.province_id 
       INNER JOIN countries as ct ON c.country_id = ct.country_id 
    where c.city_id = "requested value";
    

    【讨论】:

    • 当为了可读性而缩进很好时,你的错误变得非常明显
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2013-06-30
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    相关资源
    最近更新 更多