简体   繁体   English

基于现有值的MySQL插入选择

[英]MySQL Insert Select based on existing values

I have a method which will create duplicate (default) values for each new project we create within our task management system. 我有一种方法可以为我们在任务管理系统中创建的每个新项目创建重复的(默认)值。 At the moment it runs multiple loops based on a default =1 SELECT query and then inserts new rows based on the default values. 目前,它基于default = 1 SELECT查询运行多个循环,然后根据默认值插入新行。 These values must be duplicated on a new project (not the same). 这些值必须在新项目上重复(不相同)。

I personally feel it's using a lot of unneccesary overhead and can be tuned to work more efficiently, esspecially looking at INSERT SELECT queries, but i am not sure how to approach this. 我个人觉得它消耗了很多不必要的开销,可以调整为更有效地工作,尤其是查看INSERT SELECT查询,但是我不确定如何解决这个问题。

 public function copyProductDefaults($productID, $userID) {
    // Run loop for tasks categories:
    $sql = "SELECT `name`,`description` FROM `tasks_categories` WHERE `default`=1";
    $rows = $this->get($sql, array());
    foreach ($rows AS $row) {
        $sql = "INSERT INTO `tasks_categories` (`name`,`description`,`product_id`,`user_id`,`default`,`create_date`) VALUES (?,?,?,?,?,NOW())";
        $this->insert($sql, array($row['name'], $row['description'], $productID, $userID,0));
    }

    // Run loop for tasks types:
    $sql = "SELECT `name` FROM `tasks_types` WHERE `default`=1";
    $rows = $this->get($sql, array());
    foreach ($rows AS $row) {
        $sql = "INSERT INTO `tasks_types` (`name`,`product_id`,`user_id`,`default`,`create_date`) VALUES (?,?,?,?,?,NOW())";
        $this->insert($sql, array($row['name'], $productID, $userID,0));
    }

    // Run loop for tasks statuses:
    $sql = "SELECT `name` FROM `tasks_statuses` WHERE `default`=1";
    $rows = $this->get($sql, array());
    foreach ($rows AS $row) {
        $sql = "INSERT INTO `tasks_statuses` (`name`,`product_id`,`user_id`,`default`,`create_date`) VALUES (?,?,?,?,?,NOW())";
        $this->insert($sql, array($row['name'], $productID, $userID,0));
    }

    return true;
}

Is this what you are looking for? 这是你想要的?

INSERT INTO task_categories (name,description,product_id,user_id,`default`,create_date)
    SELECT name,description,?,?,0,now() FROM task_categories WHERE `default`=1

(and the same for the other two). (其他两个相同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM