【问题标题】:Grouping results in MySQLMySQL中的分组结果
【发布时间】:2012-09-25 21:38:20
【问题描述】:

我的大脑正在变成木薯粉,试图弄清楚这一点。我有一张下属和上司的表。每个员工都有一些课程。这是一个例子。

我有三个字段: employee_id、name、supervisor_id

Fred Wilkie 是一名主管,他的记录是……

employee_id: 1
name: Fred Wilkie
supervisor_id: NULL 

Ted Wilkie 是一个卑微的工人,而 Fred 是他的老板。他的条目是这样的......

employee_id: 2
name: Ted Wilkie
supervisor_id: 1

我希望我的查询看起来像employee_id、name 和supervisor_id,但如果supervisor_id 为NULL,则supervisor_id 应该等于employee_id。

这有点工作......(我想我只需要以某种方式对其进行改进)

select employee_id, name, supervisor_id case when supervisor_id is NULL then employee_id else supervisor_id end from employees order by supervisor_id;

这样做的问题是它首先对所有记录进行排序,其中employee_id 等于supervisor_id,然后它只是吐出剩下的下属......

employee_id, name, supervisor_id
1, Fred Wilkie, 1
4, Gail Winston, 4
2, Ted Wilkie, 1
3, Lisa Wilkie, 1
5, Russ Cablas, 4
6, Ben Reynolds, 4
etc, etc, etc...

我想要的是这个……

employee_id, name, supervisor_id
1, Fred Wilkie, 1
2, Ted Wilkie, 1
3, Lisa Wilkie, 1
4, Gail Winston, 4
5, Russ Cablas, 4
6, Ben Reynolds, 4
etc, etc, etc...

在上面的示例中,我列出了第一个主管 (Fred) (employee_id = supervisor_id),然后是他的所有下属。然后是盖尔,还有她的手下们等等。我觉得我的组夫很弱。

我们经营着一家大公司(250 名员工),因此我们想要一种方法将其保留在 MySQL 逻辑中。有人有想法吗?

非常感谢! 珍妮

【问题讨论】:

    标签: mysql group-by


    【解决方案1】:

    对此最简单的解决方案是使用COALESCE

    SELECT  employee_ID,
            name,
            COALESCE(supervisor_id, employee_id) AS supervisor_id
    FROM    employees
    ORDER BY supervisor_id, employee_ID
    

    SQLFiddle Demo

    附加查询(如果您想获取他们的主管姓名而不是 id

    SELECT  a.employee_ID,
            a.name,
            COALESCE(b.name, a.name) AS Supervisor_Name
    FROM    employees a
            LEFT JOIN employees b
              ON a.supervisor_ID = b.employee_ID
    ORDER BY COALESCE(b.supervisor_id, a.employee_id), employee_ID
    

    SQLFiddle Demo

    【讨论】:

      【解决方案2】:
      select employee_id, name, supervisor_id case when supervisor_id is NULL then employee_id else supervisor_id end from employees order by supervisor_id ASC;
      

      应该做的伎俩...

      【讨论】:

        【解决方案3】:

        我认为您缺少获取您正在使用的记录的序列order by,但没有突出序列ASCDESC

        select employee_id, name, 
        supervisor_id case when supervisor_id is NULL 
        then employee_id else supervisor_id end 
        from employees 
        order by supervisor_id
        ASC;
        

        希望这可行

        【讨论】:

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