我想转置一行表格。
例如,如果我有一个“人物”表,其中“ID”,“名字”,“姓氏”,“年龄”作为属性,我希望在“人物”表中转换一行以下两个列:
Column_name,Column_value
我可以使用以下方式获取表的列名:
SELECT *
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='databasename'
AND `TABLE_NAME`='tablename';
我尝试使用以下方法获取列名的值:
select attributes.`COLUMN_NAME`, person.attributes.`COLUMN_NAME` as `Column_Value`
from (select * from Persons where ID=1) as person,
(SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='databasename' and `TABLE_NAME`='tablename');
但第二个参数也是给出了列名而不是值。
如何解决此问题。
答案 0 :(得分:0)
您可以使用带有预准备语句的存储过程
DROP PROCEDURE IF EXISTS proc;
DELIMITER $$
CREATE PROCEDURE proc()
BEGIN
DECLARE query longtext;
SELECT
GROUP_CONCAT( CONCAT("(select '",column_name,"' as col_name,",concat("person.",column_name)," as col_val
FROM (select * from test.game_action where id=1) as person,(SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='test' and `TABLE_NAME`='game_action')as t)") SEPARATOR ' union ') into query
FROM (select * from test.game_action where id=1) as person,(SELECT * FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='test' and `TABLE_NAME`='game_action')as t;
SET @s = query;
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
如果需要,可以将id作为参数传递