[英]Updating a table joining another 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;
我收到此錯誤,您的SQL語法中有錯誤; 查看與您的MySQL服務器版本對應的手冊,以便在'FROM table1 t1 JOIN table2 t2附近使用正確的語法...
有什么想法嗎?
謝謝。
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;
測試用例:
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);
結果:
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;
我在更新加入時遇到問題。 在table1中我保存了用戶名而不是userid。 對於用戶名數據類型是varchar(10)。 當名稱超過10時,名稱僅保存10個字符。 現在,當我嘗試使用連接查詢進行更新時,它不適用於那些在用戶表中沒有精確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)
===我這樣解決了
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.