1

我有一张桌子:

CREATE TABLE `t` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(100) DEFAULT NULL,
  `priority` int(11) DEFAULT NULL,
  `val1` varchar(100) DEFAULT NULL,
  `val2` varchar(100) DEFAULT NULL,
  `val3` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `t` VALUES (1,'tj',1,'Set-1',NULL,NULL),(2,'tj',5,'Z-invalid','Set-2',NULL),(3,'tj',10,'a-invalid','Z-invalid','Set-3');

数据如下所示:

mysql> select * from t;
+----+------+----------+-----------+-----------+-------+
| id | user | priority | val1      | val2      | val3  |
+----+------+----------+-----------+-----------+-------+
|  1 | tj   |        1 | Set-1     | NULL      | NULL  |
|  2 | tj   |        5 | Z-invalid | Set-2     | NULL  |
|  3 | tj   |       10 | a-invalid | Z-invalid | Set-3 |
+----+------+----------+-----------+-----------+-------+

我想做的是按优先级排序,然后折叠或覆盖数据。如果列中的值为 NULL,则从下一个最高优先级列中获取值。如果一个字段不为空,则停在那里。

它最终应该看起来像这样:

+------+-----------+-----------+-------+
| user | val1      | val2      | val3  |
+------+-----------+-----------+-------+
| tj   | Set-1     | Set-2     | Set-3 |
+------+-----------+-----------+-------+

如果我只想获得一个领域,那很容易 - 我会做

SELECT val1 FROM t WHERE user='tj' AND val1 IS NOT NULL ORDER BY priority ASC LIMIT 1;

但是我实际上想要实现这个想法的表有大约 30 列,我不想做 30 次不同的选择。而且我不能使用 MAX,因为它是确定每列显示哪个值的优先级,而不是列本身值的 MAX。

我在这里缺少某种聚合选项吗?

4

1 回答 1

0

这有点小技巧,需要检查每一行,所以如果你的表很大,性能会很糟糕,但你可以这样做:

set @val1 = NULL;
set @val2 = NULL;
set @val3 = NULL;

select @val1 AS val1, @val2 AS val2, @val3 AS val3
from
(
  select @val1 := COALESCE(@val1, val1) AS val1, 
         @val2 := COALESCE(@val2, val2) AS val2, 
         @val3 := COALESCE(@val3, val3) AS val3
  from t 
  order by priority asc
) x
limit 1

SQL Fiddle 演示

于 2013-09-19T23:42:59.487 回答