Mysql 以另一种方式合并

Mysql 以另一种方式合并,mysql,Mysql,嗨,我有这个场景 我的桌子 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')

嗨,我有这个场景

我的桌子

 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');
以下是数据片段

 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');
表格上的注释

具有c状态的id必须具有a的先前状态,b触发没有问题

将此查询为

我在标量相关子查询中使用了distinct

[底线] 我想要一个更好的扣子来做这件事

谢谢

试试这个:

SELECT id, IF(a=0, '', a) a, IF(b=0, '', b) b, IF(c=0, '', c) c
FROM (SELECT id, SUM(IF(stage = 'a', num, '')) a, 
            SUM(IF(stage = 'b', num, '')) b, SUM(IF(stage = 'c', num, '')) c
    FROM foo GROUP BY id) AS A

@回复:正如预期的那样,它工作得很好,但我会选择eggyal的答案,因为不涉及子查询