我希望父查询在此查询中是唯一的:
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
但它会出错。
答案 0 :(得分:0)
条款的顺序不正确。你想要
select DISTINCT * ...
答案 1 :(得分:0)
从语法上讲,你应该把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
但语义可能对您的要求不合适。
答案 2 :(得分:0)
像这样重写,并获得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;