Despite what others have suggested, you can't do what you want with INSERT ... SELECT
syntax, because you've to split values and insert more than one row for each row of the source table.
You can instead write a short PHP script to do the job, I've assumed the following table structure and test data:
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL,
`assignedlessons` varchar(100) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `users` (`user_id`, `assignedlessons`) VALUES
(1, '69|308|50|91'),
(2, '56|34|7');
CREATE TABLE IF NOT EXISTS `user_assigned_elearning_lessons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`elearning_lesson_id` int(11) NOT NULL,
`created_at` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
With a PHP script you can loop over all the rows of the first table, explode the composite field into its parts and do an INSERT statement for each of those part. I've used mysqli
object oriented style with prepared statements to build the insert queries.
<?php
main();
function main() {
$source = new mysqli("localhost", "username", "password", "database");
$destin = new mysqli("localhost", "username", "password", "database");
$stmt = prepareInsertStatement($destin);
$result = $source->query("SELECT user_id, assignedlessons FROM users");
while ($user = $result->fetch_object()) {
insertUser($stmt, $user);
}
$result->close();
$source->close();
$destin->close();
}
function insertUser(&$stmt, &$user) {
$lessons = explode('|', $user->assignedlessons);
foreach ($lessons AS $lesson) {
$stmt->bind_param("ii", $user->user_id, $lesson);
$stmt->execute();
echo "User " . $user->user_id . " lesson $lesson<br/>";
}
}
function &prepareInsertStatement(&$destin) {
$sql = "INSERT INTO user_assigned_elearning_lessons
(user_id, elearning_lesson_id, created_at) VALUES (?, ?, NOW())";
$stmt = $destin->stmt_init();
$stmt->prepare($sql);
return $stmt;
}
?>
I bind the parameters to the the prepared statement with bind_param:
$stmt->bind_param("ii", $user->user_id, $lesson);
Where the "ii"
means that the type of those parameters is integer and integer.
The output with this test data will be:
User 1 lesson 69
User 1 lesson 308
User 1 lesson 50
User 1 lesson 91
User 2 lesson 56
User 2 lesson 34
User 2 lesson 7