2015-11-08 48 views
-2

我有一個表 「tbl_option」轉換行到列在MySQL

表結構和數據是這樣的:

Table structure

我要像表結構:

Ques_id Opt_1 Opt_2 Opt_3 Opt_4 
4   abc  def  ijk  lmn 

任何人都可以幫助

+0

從哪裏值'abc def ijk lmn'來? –

+2

你應該更具體一點,我們錯過了很多信息... –

+0

abc def只是例子我想要的數據在表 –

回答

0

我認爲你的源表ne編一個主鍵,那麼就應該是這樣的:

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 
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或任何你想提前。

+0

我已經做了,但它花了很多時間,因爲數據超過1000 row –

+0

@Kuldeep Singh這不是一個快速的過程重構大量數據。這使用準備好的聲明,這會使它花費更少的時間,但否則我認爲你將不得不讓它花費時間。 –