我有一张桌子:
+--------------+-------+--------+----------+
| 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连接多个表。
是否有更简单或更少的复制/粘贴方式来写这个?
答案 0 :(得分:3)
更有效的查询(至少对于大型表)是:
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
)。对于大型表,这可能是性能的显着差异。