你好,我有这个场景
我的 table
create table foo(
id int,
num int1,
stage enum('a','b','c'),
unique(id,stage)
);
这里是一段数据
INSERT INTO `foo` (`id`, `num`, `stage`) VALUES
(1, 1, 'a'),
(1, 2, 'b'),
(1, 3, 'c'),
(2, 1, 'a'),
(2, 2, 'b'),
(2, 3, 'c'),
(3, 1, 'a'),
(3, 2, 'b'),
(4, 1, 'a');
Notes on table
an id that has a state of c must have a prior state of a,b triggers no problem
查询为
I did this useing distinct with scalar correlated subquery
SELECT DISTINCT
id, IFNULL((
SELECT num
FROM foo f
WHERE f.id = foo.id AND f.stage = 'a'),'') `a`, IFNULL((
SELECT num
FROM foo f
WHERE f.id = foo.id AND f.stage = 'b'),'') `b`, IFNULL((
SELECT num
FROM foo f
WHERE f.id = foo.id AND f.stage = 'c'),'') `c`
FROM foo
[Bottom line] I want a better fasten to do this
谢谢
最佳答案
SELECT id,
MAX(IF(stage = 'a', num, NULL)) AS `a`
MAX(IF(stage = 'b', num, NULL)) AS `b`
MAX(IF(stage = 'c', num, NULL)) AS `c`
FROM foo
GROUP BY id
关于mysql - 以相反的方式合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13932427/