MySQL视图与其他表中的转置值

时间:2019-01-09 18:04:06

标签: mysql sql

我在MySQL的Google云sql数据库中有2个表,其中有一些引用:

map.click(...)
map.keydown(...)
map.keyup(...)
map.keypress(...)

一个带有一些包装的东西:

+-------+---------+--------+
| ref   | couleur | pack   |
+-------+---------+--------+
| HELLO | NOIR    | 3S2M2L |
| HELLO | WHITE   | 3S2M2L |
| WORLD | RED     | 3SM2ML |
| WORLD | GREEN   | 3SM2ML |
+-------+---------+--------+

我需要列出现有参考文件的大小:

+--------+------+------+------+------+------+
| pack   | S    | M    | L    | SM   | ML   |
+--------+------+------+------+------+------+
| 3S2M2L |    3 |    2 |    2 |    0 |    0 |
| 3SM2ML |    0 |    0 |    0 |    3 |    2 |
+--------+------+------+------+------+------+

我正在尝试这样的情况,但是当我添加另一个“ case when”替换“ null”时,这给了我一个错误。

+-------+---------+--------+
| ref   | couleur | taille |
+-------+---------+--------+
| HELLO | NOIR    | S      |
| HELLO | NOIR    | M      |
| HELLO | NOIR    | L      |
| HELLO | WHITE   | S      |
| HELLO | WHITE   | M      |
| HELLO | WHITE   | L      |
| WORLD | RED     | SM     |
| WORLD | RED     | ML     |
| WORLD | GREEN   | SM     |
| WORLD | GREEN   | ML     |
+-------+---------+--------+

我有点喜欢启动SQL,非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

衣服的大小(?)在您的数据库模型中进行了硬编码。解决方案是合并五个单独的查询,如下所示:

select * from (
  select r.ref, r.couleur, 'S' as taille 
    from _refs r join _packs p on p.pack = r.pack and p.s > 0
  union
  select r.ref, r.couleur, 'M'
    from _refs r join _packs p on p.pack = r.pack and p.m > 0
  union
  select r.ref, r.couleur, 'L'
    from _refs r join _packs p on p.pack = r.pack and p.l > 0
  union
  select r.ref, r.couleur, 'SM'
    from _refs r join _packs p on p.pack = r.pack and p.sm > 0
  union
  select r.ref, r.couleur, 'ML'
    from _refs r join _packs p on p.pack = r.pack and p.ml > 0
) x
order by ref, couleur, taille