mysql查询的唯一结果
我希望父项在此查询中是唯一的:mysql查询的唯一结果,mysql,sql,Mysql,Sql,我希望父项在此查询中是唯一的: select *, (select state_name from tbl_states where state_id = tbl_cities.parent_id) as parent from tbl_cities ORDER BY parent 我尝试使用: select *, DISTINCT (select state_name from tbl_states
select
*,
(select state_name
from tbl_states
where state_id = tbl_cities.parent_id) as parent
from
tbl_cities
ORDER BY
parent
我尝试使用:
select
*,
DISTINCT (select state_name
from tbl_states
where state_id = tbl_cities.parent_id) as parent
from
tbl_cities
ORDER BY
parent
但是它给出了一个错误。术语顺序不正确。你想要
select DISTINCT * ...
在语法上,您应该将DISTINCT放在子选择中:
select * ,
(select DISTINCT state_name
from tbl_states
where state_id = tbl_cities.parent_id) as parent
from tbl_cities ORDER BY parent
我不明白为什么会有多个状态,它们真的是重复的同一个状态吗?
如果存在不同的状态,那么您就有不同的问题。在这种情况下,就语法而言,以下操作将起作用:
select * ,
(select MAX(state_name)
from tbl_states
where state_id = tbl_cities.parent_id) as parent
from tbl_cities ORDER BY parent
但是语义可能不符合您的要求。像这样重新编写,并获得符合ANSI标准的额外好处
select
c.*, parent.state_name
from
tbl_cities c
left join (
select
state_id, state_name
from
tbl_states
group by
state_id, state_name
) as parent
on parent.state_id = c.parent_id
order by
parent.state_name;
抛出了什么错误?1064-您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以获得正确的语法,以便在第1行中使用“DISTINCT select state_name from tbl_states,其中state_id=tbl_cities.parent_i”附近的“DISTINCT select state_name from tbl_states,其中state_id=tbl_cities