mysql把一行保存到另一个表_如何将一行从一个mysql表复制到另一个mysql表

如果你已经回答了,请原谅。我已经看了很多其他的问题,没有一个是有帮助的!基本上,我想将一行从一个表复制到另一个表。我遇到的问题是,我要复制的行的id已经在使用,在我要复制到的表中。这就是我目前所拥有的,它起作用,直到它解决这个问题。

INSERT INTO venues SELECT * FROM submitted_venues WHERE id='9';

它生成错误:键“id”的重复项“9”

是否有一种方法可以动态更改id号,以便为接收表创建一个未使用的新编号,或者我是否必须编写一个查询来命名和获取每个表的所有字段。像replace语句0这样的情况会很好,0会创建一个新记录!!

9,只是我在这个例子中使用的一个数字,当然它会改变。

编辑:

我已经为这个问题创造了一个解决方案。

//get highest id number of table to copy to

$sql = "SELECT id FROM venues ORDER BY id DESC LIMIT 1";

if( $result = mysqli_query( $mysqli, $sql ) ){

$row = mysqli_fetch_array($result);

$to_id = $row[ 0 ];

//increase id

$to_id ++;

//get highest id number of table to copy from

$sql = "SELECT id FROM submitted_venues ORDER BY id DESC LIMIT 1";

if( $result = mysqli_query( $mysqli, $sql ) ){

$row = mysqli_fetch_array($result);

$from_id = $row[ 0 ];

//increase id

$from_id ++;

//get highest unused id number

$temp_id = $to_id > $from_id ? $to_id : $from_id;

//update existing record to ensure that its id number will not conflict

$sql = "UPDATE submitted_venues SET id = '$temp_id' WHERE id='$current_venue_id'";

if( $result = mysqli_query( $mysqli, $sql ) ){

$current_venue_id = $temp_id;

//copy record to normal regular venues table

$sql = "INSERT INTO venues SELECT * FROM submitted_venues WHERE id='$current_venue_id'";

if( ! $result = mysqli_query( $mysqli, $sql ) )

die("Could not copy -> " . mysqli_error($mysqli) );

//delete record from temp db table

$sql = "DELETE FROM submitted_venues WHERE id='$current_venue_id'";

if( ! $result = mysqli_query( $mysqli, $sql ) )

die("Could not delete -> " . mysqli_error($mysqli) );

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值