mysql - 从同一张表中插入两个选择

标签 mysql sql

我正在使用 insert into select 将一行从 table1 复制到 table2,除了我需要从同一个表的两个不同行中选择数据。如何做到这一点?

表一

"id"    "name"      "description"   "path"                              "country"   "status"
"1"     "Title 1"   "Description 1" "US > Consumer > Home Applicances"  "US"        "0"
"2"     "Title 2"   "Description 2" "US > Business > Legal Charges"     "UK"        "0"

表2

"id"    "name"  "description"   "path"  "newId" "newPath"   "country"   "status"

当前 SQL

insert into table2 select null, name, description, path, country, status from table1 where id=1;

尝试一次完成这两项

$currentId = 1;
$newId = 2;

// This'll update columns name, description, path, country, status
insert into table2 select null, name, description, path, country, status from table1 where id=$currentId;

// This'll need to update newId, newPath same row
insert into table2 newId, newPath from table1 where id=$newId;

//Trying to achiev    
insert into table2 select null, name, description, path, country, status from table1 where id=$currentId, insert into table2 //newId, newPath  select id, path from table1 where id=$newId;

最佳答案

使用JOIN

INSERT INTO table2
SELECT t1.id, t1.name, t1.description, t1.path, t2.id, t2.path, t1.country, t1.status
  FROM table1 t1 JOIN table1 t2
    ON t1.id = $currentId AND t2.id = $newId

这是 SQLFiddle 演示

关于mysql - 从同一张表中插入两个选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17006684/

相关文章:

php - 多重连接 Laravel

mysql语句不工作

Python MySQL 和 Django 问题

mysql - 计算MySQL中组记录的总和

mysql - hive 中的等级/组

创建触发器时出现 SQLiteException « "ON"附近的逻辑错误 »

mysql - 你能在 LEFT JOIN 之前在 MySQL 上应用 LIMIT 吗?

sql - ConcatRelated() 函数在表单上提供唯一值

sql - 如何在分页前获取不同行的总数?

mysql - mySQL 和 postgreSQL 中的 Group by 子句,为什么 postgreSQL 出错?