mysql - 以相反的方式合并

标签 mysql

你好,我有这个场景

我的 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

查询为

Heidisql output

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/

相关文章:

mysql - 从unix迭代并写入mysql

php - 创建 PHP 多用户登录

android - 将 MySQL 数据库导入到 android SQLite 数据库

php - 如何在sql数据库中搜索多个字段和多个值

mysql - 从为另一列指定了两个的表中获取行

mysql - 当并非所有数据点都匹配时合并 mySQL 中的数据

php - MYSQL 中使用 OR 语句查询数组

mysql - SQL-查找最早的 A 事件和第 N 个 B 事件之间的时间,其中 A 事件在第 N-1 个 B 事件之后

php - PDO 使用 while 和 foreach 获取

mysql - 如果子任务的标签为空,则继承父任务的标签