在MySQL中,沒有內(nèi)置的UNPIVOT函數(shù)來實現(xiàn)數(shù)據(jù)逆轉(zhuǎn)操作。但是可以使用UNION ALL語句來實現(xiàn)類似的功能。下面是一個示例:
假設(shè)有一個表格包含以下數(shù)據(jù):
| id | name | score1 | score2 | score3 |
|----|------|--------|--------|--------|
| 1 | Alice| 80 | 85 | 90 |
| 2 | Bob | 75 | 70 | 80 |
| 3 | Chris| 90 | 95 | 85 |
要將數(shù)據(jù)進(jìn)行逆轉(zhuǎn),可以使用以下SQL語句:
SELECT id, name, 'score1' AS score_type, score1 AS score
FROM table_name
UNION ALL
SELECT id, name, 'score2' AS score_type, score2 AS score
FROM table_name
UNION ALL
SELECT id, name, 'score3' AS score_type, score3 AS score
FROM table_name
執(zhí)行以上SQL語句后,會得到如下結(jié)果:
| id | name | score_type | score |
|----|------|------------|-------|
| 1 | Alice| score1 | 80 |
| 1 | Alice| score2 | 85 |
| 1 | Alice| score3 | 90 |
| 2 | Bob | score1 | 75 |
| 2 | Bob | score2 | 70 |
| 2 | Bob | score3 | 80 |
| 3 | Chris| score1 | 90 |
| 3 | Chris| score2 | 95 |
| 3 | Chris| score3 | 85 |
這樣就實現(xiàn)了將原始表中的列轉(zhuǎn)換為行的操作。