简体   繁体   English

更新连接另一个表的表

[英]Updating a table joining another table

Update a table joining 1 more table. 更新一个表加入另外一个表。

UPDATE t1 SET  t1.col1 =1 FROM table1 t1 JOIN  table2 t2 
ON t1.ID=t2.ID
WHERE t1.Name='Test' AND t2.Age=25;

i get this error,You have an error in your SQL syntax; 我收到此错误,您的SQL语法中有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM table1 t1 JOIN table2 t2 ... 查看与您的MySQL服务器版本对应的手册,以便在'FROM table1 t1 JOIN table2 t2附近使用正确的语法...

Any thoughts? 有什么想法吗?

Thanks. 谢谢。

There shouldn't be a FROM clause in the UPDATE statement, and the SET clause should follow the full set of table references: UPDATE语句中不应该有FROM子句, SET子句应该遵循完整的表引用集:

UPDATE  table1 t1 
JOIN    table2 t2 ON t1.ID = t2.ID
SET     t1.col1 = 1
WHERE   t1.Name = 'Test' AND t2.Age = 25;

Test case: 测试用例:

CREATE TABLE table1 (id int, col1 int, name varchar(20));
CREATE TABLE table2 (id int, age int);

INSERT INTO table1 VALUES (1, 0, 'Test');
INSERT INTO table1 VALUES (2, 0, 'Test');
INSERT INTO table1 VALUES (3, 0, 'No Test');

INSERT INTO table2 VALUES (1, 20);
INSERT INTO table2 VALUES (2, 25);
INSERT INTO table2 VALUES (3, 25);

Result: 结果:

SELECT * FROM table1;
+------+------+---------+
| id   | col1 | name    |
+------+------+---------+
|    1 |    0 | Test    |
|    2 |    1 | Test    |
|    3 |    0 | No Test |
+------+------+---------+
3 rows in set (0.00 sec)
UPDATE  table1 SET  col1 = 1
from table1 t1
JOIN    table2 t2 ON t1.ID = t2.ID
WHERE   t1.Name = 'Test' AND t2.Age = 25;

I have a problem in update join. 我在更新加入时遇到问题。 in table1 i saved username instead of userid. 在table1中我保存了用户名而不是userid。 And for username datatype was varchar(10). 对于用户名数据类型是varchar(10)。 When name exceeds 10 then name is saved with 10 character only. 当名称超过10时,名称仅保存10个字符。 Now when i try to update using join query it doesn't works on those fields that have not exact unername in users table, Notice name bill gat in table1 but the name in users field was bill gates -es missing. 现在,当我尝试使用连接查询进行更新时,它不适用于那些在用户表中没有精确unername的字段,请注意表1中的名称bill gat,但用户字段中的名称是账单门 - 缺少。

SELECT * FROM table1;
+------+------+---------+
| id   | col1 | created_by|
+------+------+---------+
|    1 |    0 | steve jobs|
|    2 |    1 | bill gat  |
|    3 |    0 | Jones   |
+------+------+---------+
3 rows in set (0.00 sec)

===I solved this way ===我这样解决了

    UPDATE table1 AS tr
JOIN users AS u ON u.name LIKE CONCAT('%', tr.created_by, '%')
SET tr.created_by=u.id
WHERE tr.created_by IS NOT NULL

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

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