我有两张结构相同的桌子。 Table1
保留审核数据,table2
保留其余数据。
表1
+------+--------+---------------+--------+-----------+ | "id" | "name" | "description" | "type" | "country" | +------+--------+---------------+--------+-----------+ | "1" | "a" | "x" | "1" | "US" | | "2" | "b" | "x" | "1" | "UK" | +------+--------+---------------+--------+-----------+
表2
+------+-----------+-----------------+--------+-----------+----------+ | "id" | "name" | "description" | "type" | "country" | "status" | +------+-----------+-----------------+--------+-----------+----------+ | "1" | "Title 1" | "Description 1" | "1" | "US" | "0" | | "2" | "Title 2" | "Description 2" | "10" | "UK" | "0" | +------+-----------+-----------------+--------+-----------+----------+
我运行下面的sql以使用来自table 1
的数据更新table 2
,并且效果很好。唯一的问题是,我需要在两个地方指定id
。如果我只在一个地方指定它,它会去哪里?
UPDATE table1 dest,
(SELECT name,
description
FROM table2
WHERE id = 1) src
SET dest.name = src.name,
dest.description = src.description
WHERE dest.id = 1;
这件事的方式是:
UPDATE table1 SET name AND description =
(
SELECT name, description from table2
WHERE id=1 AND country=us and type=10
) WHERE id=idfromselect AND country=countryfromselect AND type=typefromselect
我无法确定id
和remaining conditions
的放置位置。你能帮忙吗?
答案 0 :(得分:1)
将它作为连接,将id放在连接条件中,只检查WHERE子句中的id。
这样的事情: -
UPDATE table1 dest INNER JOIN table2 src ON dest.id = src=id
SET dest.name = src.name, dest.description = src.description
WHERE dest.id=1 ;
任何其他限制都可以添加到WHERE子句
答案 1 :(得分:1)
我认为您可以使用INNER JOIN
查询根据table2中的数据更新您的table1,并将您的条件放在WHERE
子句中
UPDATE table1 a
INNER JOIN table2 b
ON a.id = b.id
SET a.name = b.name,
a.description = b.description
WHERE a.id=1;