将行转换为 mysql 中的列

Converting Row into Column in mysql

我有一个table"tbl_option"

table结构和数据是这样的:

我想要 table 结构如下:

Ques_id   Opt_1    Opt_2    Opt_3    Opt_4
4         abc      def      ijk      lmn

谁能帮忙

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

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

这取决于每条记录当前的主键是什么。如果主键只是一个任意的自动递增整数,那么最好的办法是用您选择的语言编写一个脚本,将记录转换成您想要的格式。在 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 的新 table 或您想要的任何内容。