【问题标题】:Unique results from mysql querymysql查询的唯一结果
【发布时间】:2013-02-04 19:35:27
【问题描述】:

我希望 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

但它给出了一个错误。

【问题讨论】:

  • 抛出了什么错误?
  • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在“DISTINCT”附近使用正确的语法(在第 1 行从 tbl_states where state_id = tbl_cities.parent_i 中选择 state_name

标签: mysql sql


【解决方案1】:

术语的顺序不正确。你想要的

select DISTINCT * ...

【讨论】:

    【解决方案2】:

    从语法上讲,您应该将 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
    

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

    【讨论】:

      【解决方案3】:

      像这样重写,并获得符合 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;
      

      【讨论】:

        猜你喜欢
        • 2011-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多