Is there any query that can do database modification from one column to multiple columns?
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
精彩评论