3

I have old table which the data stored as

tbl_id  tbl_data
--------------------
1       1,2,3,4,5,6
2       3,4,5

Now I want convert these to many-to-many relationship table.

user_id user_option
-------------------
1       1  
1       2
1       3
...

Basically I insert the data in php

$old = explode(",", $data['tbl_data']);
$query = $db->query("SELECT tbl_id, tbl_data FROM old_table"); 
  while($fetch = $db->fetch($query)) {
    $db->query("INSERT INTO new_table SET .....");
  }

May I know, there have a way to get this done with single MySQL statement?

1
  • 2
    +1 For the initiative to properly normalize this data. Commented Apr 29, 2012 at 13:21

1 Answer 1

2

No, you are best off to do it in PHP code. Though MySQL does have a way to locate values via FIND_IN_SET(), it doesn't have an equivalent method to explode() to easily separate them. It would be possible to write a lot of ugly looping and string manipulation in a MySQL procedure, but it's much easier to do in PHP code.

There are some suggestions for handling string splitting in the comments beneath the MySQL string function docs but they don't really address looping inserts to normalize out a column. It really is easier to just handle in a scripting lanugage like PHP.

But it is good that you are sorting this out and properly normalizing the column.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Michael. Looks like FIND_IN_SET() fit to my need at the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.