0

我希望 parent 在此查询中是唯一的:

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

但它给出了一个错误。

4

3 回答 3

0

The order of terms is incorrect. You want

select DISTINCT * ...
于 2013-02-19T22:46:07.110 回答
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

但是语义可能不符合您的要求。

于 2013-02-19T22:50:32.950 回答
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;
于 2013-02-19T22:51:21.077 回答