我的大脑正在变成木薯粉,试图弄清楚这个问题。我有一张下属和主管的表。每个员工都有一个数字当然。这是一个例子。
我有三个字段: employee_id, 姓名, supervisor_id
Fred Wilkie 是一名主管,他的记录是......
employee_id: 1
name: Fred Wilkie
supervisor_id: NULL
Ted Wilkie 是一名低级 worker ,而 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 逻辑中。有人有想法吗?
非常感谢! 珍妮
最佳答案
最简单的解决方案是使用 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
关于mysql - 在 MySQL 中对结果进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12591437/