我将表名设置为“ Employee”,并带有相应的列(id,employee_id和status)。如果状态为“待定”,则将状态为“ employee_id”,并查询到employee_id列的其他记录。因此,存在employee_id,然后我必须获取id值并将其存储到result_id中。
id employee_id status
1 1000 failed
2 1001 failed
3 1002 failed
4 1005 failed
5 1006 failed
6 1005 pending
7 1004 pending
8 1001 pending
9 1002 pending
10 1006 pending
示例:id = 6,employee_id = 1005并且status ='pending',那么result_id应该为4(即result_id = 4)
输出:
id result_id
1 NULL
2 NULL
3 NULL
4 NULL
5 NULL
6 4
7 NULL
8 2
9 3
10 5
我尝试过:
select e.id as id ,e2.id as result_id
from employee as e, employee as e2
where e.employee_id=e2.employee_id and e.id not in (e2.id)
此查询将仅返回result_id
的值,但我也需要Null值。
有人可以帮我吗?
答案 0 :(得分:0)
检查:
模式(MySQL v5.7)
CREATE TABLE t (
`id` INTEGER,
`employee_id` INTEGER,
`status` VARCHAR(12)
);
INSERT INTO t
(`id`, `employee_id`, `status`)
VALUES
('1', '1000', 'failed'),
('2', '1001', 'failed'),
('3', '1002', 'failed'),
('4', '1005', 'failed'),
('5', '1006', 'failed'),
('6', '1005', 'pending<br/>'),
('7', '1004', 'pending<br/>'),
('8', '1001', 'pending<br/>'),
('9', '1002', 'pending<br/>'),
('10', '1006', 'pending<br/>');
查询#1
select id, null x from t where status = 'failed'
union all
select t.id, t2.id from t
left join t t2
on t.employee_id = t2.employee_id and t2.status = 'failed'
where t.status != 'failed';
| id | x |
| --- | --- |
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 8 | 2 |
| 9 | 3 |
| 6 | 4 |
| 10 | 5 |
| 7 | |