在實際的數據庫應用中,經常需要對數據進行轉換,把縱表轉換成橫表。MySQL提供了一些函數,方便進行這種轉換。下面介紹幾種常用的函數。
1. GROUP_CONCAT 語法:GROUP_CONCAT(expression) 功能:將同一組的多個值行轉化為一行,并用逗號分隔 示例: SELECT GROUP_CONCAT(name) FROM student; 結果: +--------------------------+ | GROUP_CONCAT(name) | +--------------------------+ | Tom,Jack,Mary | +--------------------------+ 2. GROUP_CONCAT+CONCAT 語法:SELECT GROUP_CONCAT(CONCAT(col1,'-',col2,'-',col3) SEPARATOR ' ') AS columns FROM tablename; 功能:將多個列合并成一列,用分隔符進行分隔 示例: SELECT GROUP_CONCAT(CONCAT(name,'-',age) SEPARATOR ' ') AS student_info FROM student; 結果: +------------------------------+ | student_info | +------------------------------+ | Tom-20,Jack-22,Mary-21 | +------------------------------+ 3. CASE+GROUP_CONCAT 語法:SELECT GROUP_CONCAT(CASE TYPE WHEN ‘A’ THEN VALUE END) AS A, GROUP_CONCAT(CASE TYPE WHEN ‘B’ THEN VALUE END) AS B, GROUP_CONCAT(CASE TYPE WHEN ‘C’ THEN VALUE END) AS C FROM tablename GROUP BY NAME 功能:將原表的行列轉化成多行,每列數據分別生成一列,用于分析統計 示例: SELECT name, GROUP_CONCAT(CASE course WHEN 'math' THEN score END) AS math, GROUP_CONCAT(CASE course WHEN 'english' THEN score END) AS english, GROUP_CONCAT(CASE course WHEN 'history' THEN score END) AS history FROM score GROUP BY name; 結果: +------+--------+---------+---------+ | name | math | english | history | +------+--------+---------+---------| | Tom | 80 | 85 | 70 | | Jack | 90 | 78 | 80 | | Mary | 75 | 88 | 87 | +------+--------+---------+---------+ 以上三種函數是常用的縱表轉橫表函數,在實際應用中,可以根據需求自行調整。
上一篇mysql純凈版
下一篇mysql線上數據庫