doucheng1891 2011-11-30 11:00
浏览 22
已采纳

使用php和mysql从多个表复制行

I'm building a copy campaign function for an app and the way I did it was using loops to go through all the selected rows with php, get their IDs and loop again to insert new rows with same data but with one changed column value. This is my current approach which works perfectly:

<?php
    $id = Url::find('id');
    //Copy campaign row
    $cid = $this->Db->Query("
        INSERT INTO campaigns (`user_id`, `tid`, `featured`, `opt`, `title`, `uri`, `cpi`, `payout`, `cat`, `domain`, `created`, `disabled`, `completed`, `featured_pos`)
        SELECT `user_id`, `tid`, `featured`, `opt`, CONCAT(`title`,' - Copy'), `uri`, `cpi`, `payout`, `cat`, `domain`, `created`, `disabled`, `completed`, `featured_pos` FROM campaigns WHERE id = :id
    ",array(':id' => array(DB::INT => $id)),true);

    //Copy variants
    $vars = $this->Db->selectAll(array('cid' => $id), 'variations');
    if(!empty($vars)) {
        for($i = 0; $i < count($vars); $i++) {
            $old[] = $vars[$i]['id']; //Copy source
            $vid[] = $this->Db->Query("
                INSERT INTO variations (`ordering`, `disabled`, `cid`, `height`, `width`, `bgcolor`, `head`,`title`, `keywords`, `description`, `link`)
                SELECT `ordering`, `disabled`, :cid, `height`, `width`, `bgcolor`, `head`, `title`, `keywords`, `description`, `link` FROM variations WHERE id = :id
                ",array(
                    ':id' => array(DB::INT => $vars[$i]['id']),
                    ':cid' => array(DB::INT => $cid)
                ),true);
        }
    }
    //Copy elements
    if(isset($vid)) {
        for($i = 0; $i < count($vid); $i++) {
            $this->Db->Query("
                INSERT INTO elements (`name`, `var`, `type`, `left`, `top`, `width`, `height`, `z-index`, `html`, `css`)
                SELECT `name`, :vid, `type`, `left`, `top`, `width`, `height`, `z-index`, `html`, `css` FROM elements WHERE var = :id
                ",array(
                    ':vid' => array(DB::INT => $vid[$i]),
                    ':id' => array(DB::INT => $old[$i])
                ),true);
        }
    }
    echo "OK";
    ?>

However I'm sure this isn't the best approach as it executes way too many queries. I've upgraded the script, but I can't figure out how to copy rows to the elements table with new IDs of new variations. The new script:

$id = Url::find('id');
$cid = $this->Db->Query("
    INSERT INTO campaigns (`user_id`, `featured`, `title`, `domain`, `created`, `disabled`, `featured_pos`)
    SELECT :user, `featured`, CONCAT(`title`,' - Copy'), `domain`, `created`, `disabled`, `featured_pos` FROM campaigns WHERE id = :id
",array(':id' => array(DB::INT => $id), ':user' => array(DB::INT => $this->session->user['id'])),true);

//Copy variants

$this->Db->Query("
    INSERT INTO variations (`ordering`, `disabled`, `cid`, `height`, `width`, `bgcolor`, `head`,`title`, `keywords`, `description`, `link`)
    SELECT `ordering`, `disabled`, :id, `height`, `width`, `bgcolor`, `head`, `title`, `keywords`, `description`, `link` FROM variations WHERE cid = :oid
",array(
    ':id' => array(DB::INT => $cid), //new id
    ':oid' => array(DB::INT => $id) //old id
 ),true);

 $this->Db->Query("
    INSERT INTO elements (`name`, `var`, `html`, `type`)
    SELECT e.name, v.id, e.html, e.type FROM elements AS e, variations AS v
    WHERE v.cid = :cid AND e.var = v.id
",array(
    ':cid' => array(DB::INT => $id)
 ),true);

The first 2 queries work as expected, however the last one (INSERT INTO elements) doesn't . That's because it selects the variations from the old campaign, and inserts into var column the old ids instead of previously inserted new ones. Obviously that's because the query is built this way but how do I get the IDs from the new variations without a loop to insert them into elements. (Or am I paranoid too much and my initial approach is fine?)

To be more clear with my question - how do I do this without a php loop:

    INSERT INTO elements (`name`, `var`, `html`, `type`)
    SELECT e.name, (new v.id from the previous query and not the same one as in WHERE clause), e.html, e.type FROM elements AS e, variations AS v
    WHERE v.cid = :cid AND e.var = v.id

Sorry for my grammar mistakes (I just got to work and need a coffee)

Thanks a lot :)

  • 写回答

2条回答 默认 最新

  • douzhimao8656 2012-04-26 20:44
    关注

    Not very sure that I understood what you were asking, because, as a matter of fact, your question included way too much information for the cause. I will try to answer only your last question:

    INSERT INTO elements (`name`, `var`, `html`, `type`)
        SELECT e.name, (new v.id from the previous query and not the same one as in WHERE clause), e.html, e.type FROM elements AS e, variations AS v
        WHERE v.cid = :cid AND e.var = v.id
    

    Again, don't be harsh if I missed the point :)

    So you insert a bunch of rows, then based on the ID's of those, you want to insert them into different table? So if it is only you, who is using the system, the simple approach would be just taking the ID's of the inserted rows like for example if you know the amount of inserted rows, just simply take the last n rows? Or add another column with a unique id, so you can take from it only. Then having the ID's in array, join them with a colon and finally, your query should look like this:

    INSERT INTO elements (`name`, `var`, `html`, `type`)
        SELECT e.name, (new v.id from the previous query and not the same one as in WHERE clause), e.html, e.type FROM elements AS e, variations AS v
        WHERE v.cid IN($c_ids) AND e.var IN($v_ids)
    

    So in summary: -insert -take inserted c ids -insert -take inserted v ids -join c ids -join v ids -use the query

    And I have no clue how the query works with something like this:

    INSERT INTO campaigns (`user_id`, `featured`, `title`, `domain`, `created`, `disabled`, `featured_pos`)
        SELECT :user, `featured`, CONCAT(`title`,' - Copy'), `domain`, `created`, `disabled`, `featured_pos` FROM campaigns WHERE id = :id
    ",array(':id' => array(DB::INT => $id)
    

    I really do hope it does not insert 1000 rows one by one. However if it does (and I guess you are paranoid about that), use joins in php so it reduces the amount of text sent to sql and especially the amount of queries called. If the numbers of rows are high, the amount of time spent will be ridiculously huge.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗