我有一个带有一些名称引用的表。
使用查询:
SELECT id, n1, n2, n3
FROM nametable
表返回:
+----+--------+-------+--------+ | id | n1 | n2 | n3 | +----+--------+-------+--------+ | 1 | Larry | Bob | Mo | | 2 | Sara | May | (NULL) | | 3 | Keiran | Lenny | (NULL) | +----+--------+-------+--------+
我想把它作为:
+----+--------+ | id | n | +----+--------+ | 1 | Larry | | 1 | Bob | | 1 | Mo | | 2 | Sara | | 2 | May | | 3 | Keiran | | 3 | Lenny | +----+--------+
请注意,最终结果
中不会返回(NULL)值我做了一些研究,发现了一个叫做“数据透视表”的东西。但是,没有一个例子符合我的条件。我希望在每一行都保留id。
我如何使用查询?
答案 0 :(得分:3)
我认为这是mysql中最接近的:
select * from (
(select id, n1 as n from nametable) union all
(select id, n2 as n from nametable) union all
(select id, n3 as n from nametable)
) x
答案 1 :(得分:0)
您也可以通过这种方式取消对您的牌照
SELECT id,
CASE n
WHEN 1 THEN n1
WHEN 2 THEN n2
WHEN 3 THEN n3
END n
FROM nametable t CROSS JOIN
(
SELECT 1 n UNION ALL
SELECT 2 UNION ALL
SELECT 3
) i
HAVING n IS NOT NULL
ORDER BY id, n;
输出:
| ID | N | |----|--------| | 1 | Bob | | 1 | Larry | | 1 | Mo | | 2 | May | | 2 | Sara | | 3 | Keiran | | 3 | Lenny |
这是 SQLFiddle 演示