我有一张 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/