gpt4 book ai didi

mysql - 将垂直表转换为水平表

转载 作者:行者123 更新时间:2023-11-29 07:30:32 25 4
gpt4 key购买 nike

我正在为这个操作寻找一个干净、快速和漂亮的解决方案。首先我有一个看起来像这样的表

field_id   -    item_id   -   value
1 - 781 - name1
2 - 781 - lastname1
3 - 781 - phone1
1 - 782 - name2
2 - 782 - lastname2
3 - 782 - phone2
1 - 783 - name3
2 - 783 - lastname3
3 - 783 - phone3

我想像这样显示这个表:

item_id    -    name   -   lastname   -   phone
781 - name1 - lastname1 - phone1
782 - name2 - lastname2 - phone2
783 - name3 - lastname3 - phone3

我试过了

SELECT field_id, item_id,
(CASE WHEN field_id = 1 THEN value END) AS name,
(CASE WHEN field_id = 2 THEN value END) AS lastname,
(CASE WHEN field_id = 3 THEN value END) AS phone
FROM cq6xb_fields_values
GROUP BY item_id;

但是我得到了这个奇怪的结果

item_id    -    name   -   lastname   -   null 
781 - null - lastname1 - null
782 - null - lastname2 - null
783 - null - lastname3 - null

最佳答案

你不远只是添加 max 并且你可以删除字段 id 因为你没有使用它。

SELECT item_id,
max(CASE WHEN field_id = 1 THEN value END) AS name,
max(CASE WHEN field_id = 2 THEN value END) AS lastname,
max(CASE WHEN field_id = 3 THEN value END) AS phone
FROM cq6xb_fields_values
GROUP BY item_id;

+---------+-------+-----------+--------+
| item_id | name | lastname | phone |
+---------+-------+-----------+--------+
| 781 | name1 | lastname1 | phone1 |
| 782 | name2 | lastname2 | phone2 |
| 783 | name3 | lastname3 | phone3 |
+---------+-------+-----------+--------+
3 rows in set (0.00 sec)

关于mysql - 将垂直表转换为水平表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51490283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com