在mysql中将行转换为列

时间:2015-11-08 10:10:41

标签: mysql pivot

我有一张桌子“tbl_option”

表格结构和数据如下:

Table structure

我希望表结构如下:

Ques_id   Opt_1    Opt_2    Opt_3    Opt_4
4         abc      def      ijk      lmn

任何人都可以提供帮助

2 个答案:

答案 0 :(得分:0)

我认为你的源表需要一个主键,那么它应该是这样的:

CREATE TABLE `test_table` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `q_id` int(11) unsigned DEFAULT NULL,
    `text` varchar(256) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `test_table` (`id`, `q_id`, `text`)
VALUES
    (1,1,'test'),
    (2,1,'bbb'),
    (3,1,'aaa'),
    (4,1,'ccc'),
    (5,2,'zzz'),
    (6,2,'yyy'),
    (7,2,'xxx'),
    (8,2,'www');

然后这个查询可能会有所帮助:

SELECT a.q_id, a.text t_1, b.text t_2, c.text t_3, d.text t_4
from test_table a
inner join test_table b on a.q_id = b.q_id 
inner join test_table c on b.q_id = c.q_id
inner join test_table d on c.q_id = d.q_id
where
a.id != b.id and
a.id != c.id and
a.id != d.id and
b.id != c.id and
b.id != d.id and
c.id != d.id
group by a.q_id

结果如下:

q_id    t_1 t_2 t_3 t_4
1       ccc aaa bbb test
2       www xxx yyy zzz

答案 1 :(得分:0)

这取决于每条记录的当前主键是什么。如果主键只是一个任意自动递增的整数,那么最好的办法是用您选择的语言编写一个脚本,将记录转换为您想要的格式。在PHP中,使用PDO,我会做这样的事情:

$db = //Your connection string here
$question_ids = $db->query("SELECT DISTINCT int_question_id FROM tbl_option");
foreach ($question_ids as $value) {
    $get_questions = $db->prepare("SELECT txt_option FROM tbl_option WHERE int_question_id = :question_id")
    $get_questions->execute(array(":question_id" => $value))
    $questions = $get_questions->fetchAll();      
    $insert_questions = $db->prepare("INSERT INTO tbl_new_option (Ques_id,Opt_1,Opt_2,Opt_3,Opt_4) VALUES (:question_id,:option1,:option2,:option3,:option4)");
    $insert_questions->execute(array(":question_id" => $value,":option1" => $questions[0], ":option2" => $questions[1], ":option3" => $questions[2], ":option4" => $questions[3]));
}

当然,您必须事先设置名为tbl_new_option的新表或任何您想要的表。