mysql - 将列转换为行

标签 mysql

我有一张 table :

+--------------+-------+--------+----------+
| attribute_id | color | brand  | category |
+--------------+-------+--------+----------+
|            1 | red   | honda  | cars     |
|            2 | blue  | bmw    | cars     |
|            3 | pink  | skonda | vans     |
+--------------+-------+--------+----------+

我想将其转换为以下内容:

+--------------+---------+
| attribute_id | keyword |
+--------------+---------+
|            1 | red     |
|            2 | blue    |
|            3 | pink    |
|            1 | honda   |
|            2 | bmw     |
|            3 | skonda  |
|            1 | cars    |
|            2 | cars    |
|            3 | vans    |
+--------------+---------+

我能想到的唯一方法是像这样使用 UNION:

SELECT attribute_id, color from attributes 
UNION ALL
SELECT attribute_id, brand from attributes
UNION ALL
SELECT attribute_id, category from attributes

上面的方式有点麻烦,特别是因为我的实际用例需要为每个选择连接多个表。

是否有更简单或更少的复制/粘贴方式来编写此代码?

最佳答案

一个更有效的查询(至少对于大表)是:

SELECT attribute_id,
       (case when n = 1 then color
             when n = 2 then brand
             when n = 3 then category
        end) as keyword
from attributes a cross join
     (select 1 as n union all select 2 union all select 3) n;

这比 union all 查询更好的原因是性能。 union all 将扫描原始表三次。这将扫描原始表一次(然后循环遍历 n)。对于大型表,这可能会在性能上产生显着差异。

关于mysql - 将列转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21190608/

相关文章:

mysql - MAX 或 ALL in sql

mysql - 用 MySQL 查询替换 html 样式属性

实时数据库上的 MySQL 查询速度慢,本地速度快?

mysql - 从 MySql 移植到 SQLite 代码后,VIEW 创建不起作用

MySQL 查询删除位于 ExpressionEngine 中的三个表中的 200,000 个垃圾邮件成员

php - laravel eloquent where like 整数运算符

MySQL JSON 数据类型存储历史价格

php - 我想通过使用表显示来从 MySQL 数据库检索数据,按照图像中显示的方式排列它

php - 如何在 PHP 中将 printf 添加到成功的查询返回中

mysql - 如何使用 mysql 转储数据库(服务器上没有 mysqldump)