从逗号分隔的列中获取不同的值,并在mysql中的另一个表中插入

时间:2016-10-21 06:09:23

标签: mysql

我在MySQL表中有一个列,该列由列中的逗号分隔值组成,并且同一列中有各种重复值。数据如下所示 -

select id,category_ids from tableName; +---------+-----------------------+ | id | category_ids | +---------+-----------------------+ | 1062810 | 4,7,2,2,2,2,4,7 | | 1062812 | 4 | | 1062814 | 7,7,7,7,7,7,7,7 | | 1062850 | 2,2,2,2,2,2,2,2,2,2,2 | | 1063294 | 6,6,6,6,6,6,6,6,6,6,6 |

和Out put应该是

+---------+-----------------------+ | id | category_ids | +---------+-----------------------+ | 1062810 | 4,7,2 | | 1062812 | 4 | | 1062814 | 7 | | 1062850 | 2 | | 1063294 | 6 |

请帮助我,我是mysql的新手

1 个答案:

答案 0 :(得分:1)

试试这个:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "select id,category_ids from tableName";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $id = $row["id"];
        $category_ids = array_unique(explode(',',$row["category_ids"]));

        $update_sql = "update tableName category_ids='".implode($category_ids,',')."' where id = ".$id ;
        $res = $conn->query($update_sql,$conn);

        echo "Update ID-".$id." Category ids:" .$row["category_ids"]. " Into " . implode($category_ids,','). "<br>";
    }
} else {
    echo "No data in your table";
}
$conn->close();