抱歉,我应该更具体地回答我的问题:
这是我当前的问题
我有一张桌子,上面有:
Customer_ID H2_1 H2_2 H2_3 H2_4 H2_5
123 7 3 13 5 2
456 7 3 13 5 2
789 7 3 13 5 2
我需要它看起来像这样:
Customer_ID H2_Code
123 7
123 3
123 13
123 5
123 2
456 7
456 3
456 13
456 5
456 2
789 7
789 3
789 13
789 5
答案 0 :(得分:1)
您需要UNION ALL
来组合所有列:
SELECT Customer_ID, H2_1 AS H2_Code
FROM table t
UNION ALL
SELECT Customer_ID, H2_2
FROM table t
UNION ALL
SELECT Customer_ID, H2_3
FROM table t
UNION ALL
SELECT Customer_ID, H2_4
FROM table t
UNION ALL
SELECT Customer_ID, H2_5
FROM table t
答案 1 :(得分:1)
您似乎想要union all
:
select Customer_ID, H2_1 as h2_code from t
union all
select Customer_ID, H2_2 as h2_code from t
union all
select Customer_ID, H2_3 as h2_code from t
union all
select Customer_ID, H2_4 as h2_code from t
union all
select Customer_ID, H2_5 as h2_code from t;
请注意,union all
需要扫描表格5次。对于中小型表,这不是问题。对于较大的表,有一些稍微复杂的机制,它们只会扫描一次表。
答案 2 :(得分:0)
您可能希望合并获取每个H2_something的不同查询,然后按customer_id进行订购
模式(MySQL v5.7)
CREATE TABLE tableName (
`Customer_ID` INTEGER,
`H2_1` INTEGER,
`H2_2` INTEGER,
`H2_3` INTEGER,
`H2_4` INTEGER,
`H2_5` INTEGER
);
INSERT INTO tableName
(`Customer_ID`, `H2_1`, `H2_2`, `H2_3`, `H2_4`, `H2_5`)
VALUES
('123', '7', '3', '13', '5', '2'),
('456', '7', '3', '13', '5', '2'),
('789', '7', '3', '13', '5', '2');
查询#1
SELECT customer_Id, H2_1 AS H2_Code FROM tableName
UNION ALL
SELECT customer_Id, H2_2 FROM tableName
UNION ALL
SELECT customer_Id, H2_3 FROM tableName
UNION ALL
SELECT customer_Id, H2_4 FROM tableName
UNION ALL
SELECT customer_Id, H2_5 FROM tableName
ORDER BY customer_Id;
| customer_Id | H2_Code |
| ----------- | ------- |
| 123 | 3 |
| 123 | 13 |
| 123 | 5 |
| 123 | 2 |
| 123 | 7 |
| 456 | 3 |
| 456 | 13 |
| 456 | 5 |
| 456 | 2 |
| 456 | 7 |
| 789 | 7 |
| 789 | 3 |
| 789 | 13 |
| 789 | 5 |
| 789 | 2 |
答案 3 :(得分:0)
请注意,规范化的架构通常看起来像这样:
Customer_ID H2 val
123 1 7
123 2 3
123 3 13
123 4 5
123 5 2
456 1 7
456 2 3
456 3 13
456 4 5
456 5 2
789 1 7
789 2 3
789 3 13
789 4 5
789 5 2