开发者

Is there any query that can do database modification from one column to multiple columns?

开发者 https://www.devze.com 2023-03-01 06:39 出处:网络
I am using MySQL. I have a table called entries. This table has a column called body. The body column has string data (about 500 words long).

I am using MySQL. I have a table called entries. This table has a column called body. The body column has string data (about 500 words long).

Now, I want transfer above body column into column_1,column_2,.... c开发者_开发技巧olumn_300 which contains nth word in each body column. So, if body column has a data like "I ate a lunch today", then column_1 would have 'I' , column_2 would have 'ate', and so on. I guess I can work this in PHP, but I have been wondering if it is possible in query in MySQL.


See: Split value from one field to two


Here you have a php solution.

<?php
  //Connect to mysql server
  $cn = mysql_pconnect("server", "username", "password");
  mysql_select_db("database_name");
  $rs = mysql_query("SELECT id, body FROM entries", $cn);  

  //Traverse each entry row      
  while($row = mysql_fetch_array($rs)){
     list($id, $body) = $row;
     $words = explode(" ", $body); //split by spaces (can be improved)
     $sqlUpdate = "UPDATE entries SET ";
     $sets = array();
     //Traverse words
     for($i=1; i<=count($words); $i++){
        $word_for_mysql = mysql_escape_string($words[$i-1]); //$i-1 cause arrays are zero-based index
        $sets[] = "column_$i = '$word_for_mysql'"; //i.e: column_1 = 'lorem'
     }
     $sqlUpdate.= join(", ", $sets)." WHERE id='$id'";     
     mysql_query($sqlUpdate, $cn);
  }
?>

Anyway, I wonder why you want to do this

0

精彩评论

暂无评论...
验证码 换一张
取 消