mysql - 同一个表内的Left Join SQL

标签 mysql sql

SELECT 

`_conf_cities`.`cityid`,
`_conf_cities`.`countryid`,
`_conf_cities`.`name_mkd`,
`_conf_cities`.`child_municipality`,
`_conf_cities`.`parent`,

`conf_countries`.`countryid`,
`conf_countries`.`alpha2`

FROM `_conf_cities`

LEFT JOIN `conf_countries` ON `_conf_cities`.`countryid` = `conf_countries`.`countryid`

LEFT JOIN `_conf_cities` ON  `_conf_cities`.`cityid` = `_conf_cities`.`parent`

WHERE `_conf_cities`.`child_municipality` = '0'

当我尝试LEFT JOIN _conf_cities自身时,就会出现问题。

可以用其他方式完成吗?

最佳答案

您必须使用别名,例如:

SELECT 
_conf_cities.cityid,
_conf_cities.countryid,
_conf_cities.name_mkd,
_conf_cities.child_municipality,
_conf_cities.parent,
conf_countries.countryid,
conf_countries.alpha2,
t2.cityid -- Now you can use alias
FROM _conf_cities
LEFT JOIN conf_countries ON _conf_cities.countryid = conf_countries.countryid
LEFT JOIN _conf_cities AS t2 ON  _conf_cities.cityid = t2.parent
WHERE
    _conf_cities.child_municipality = '0'
    AND t2.child_municipality = '0' -- Also you can use alias here

关于mysql - 同一个表内的Left Join SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942601/

相关文章:

mysql - 如何包含缺少一半连接的记录?

mysql - 为什么当我在 MySQL 中执行 LEFT JOIN 时它不会减少行查找的数量?

php - 如何将两种形式作为参数传递给 laravel Controller ?

mysql - Sphinx 索引器“无错误”错误

php - 优化小型 MySQL 连接查询

php - MySQL SQL语法错误;查看与您的 MySQL 服务器版本相对应的手册,了解要使用的正确语法

sql - 更新主表的复杂sql查询

mysql - 'decimal(10,2)' 附近的存储过程语法错误

mysql - (A 加入 B) 加入 (C 加入 D)

python - 1241, 'Operand should contain 1 column(s)' Pandas to_sql