我在MySQL中编写了以下SQL语句:
USE my_database;
SELECT * FROM some_table WHERE some_column IN (1, 2, 3);
这将返回一组行,这些行的列值是另一个表的一行中的键(称为some_other_table
)。
a b c d <--this is the column with the key
1
2
3
我想说,查找另一个表中值为1的所有行,然后执行某些操作(将某些列置空)
感谢任何帮助。
答案 0 :(得分:1)
是的,您可以使用多表UPDATE
语法:
UPDATE some_other_table
JOIN some_table ON (some_table.some_key = some_other_table.id)
SET some_other_table.some_field = NULL
WHERE some_table.some_column IN (1, 2, 3);
示例:
CREATE TABLE some_table (id int, some_column int, some_key int);
CREATE TABLE some_other_table (id int, some_field int);
INSERT INTO some_table VALUES (1, 1, 1);
INSERT INTO some_table VALUES (2, 2, 2);
INSERT INTO some_table VALUES (3, 3, 3);
INSERT INTO some_table VALUES (4, 4, 4);
INSERT INTO some_table VALUES (5, 5, 5);
INSERT INTO some_other_table VALUES (1, 10);
INSERT INTO some_other_table VALUES (2, 20);
INSERT INTO some_other_table VALUES (3, 30);
INSERT INTO some_other_table VALUES (4, 40);
在:
SELECT * FROM some_table;
+------+-------------+----------+
| id | some_column | some_key |
+------+-------------+----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | 4 | 4 |
| 5 | 5 | 5 |
+------+-------------+----------+
5 rows in set (0.00 sec)
SELECT * FROM some_other_table;
+------+------------+
| id | some_field |
+------+------------+
| 1 | 10 |
| 2 | 20 |
| 3 | 30 |
| 4 | 40 |
+------+------------+
4 rows in set (0.00 sec)
后:
SELECT * FROM some_table;
+------+-------------+----------+
| id | some_column | some_key |
+------+-------------+----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
| 4 | 4 | 4 |
| 5 | 5 | 5 |
+------+-------------+----------+
5 rows in set (0.00 sec)
SELECT * FROM some_other_table;
+------+------------+
| id | some_field |
+------+------------+
| 1 | NULL |
| 2 | NULL |
| 3 | NULL |
| 4 | 40 |
+------+------------+
4 rows in set (0.00 sec)
更新:继续以下评论。
另一个例子:
CREATE TABLE amir_effective_reference (class int, inst int, rln int, rclass int, rinst int, chg int, typ int);
CREATE TABLE amir_effective_change (chg int, txn int, rltn int, entry int, effective int);
INSERT INTO amir_effective_reference VALUES (1, 100, 1, 50, 20, 10, 5000);
INSERT INTO amir_effective_change VALUES (10, 100, 100, 500, 200);
结果:
UPDATE amir_effective_change
JOIN amir_effective_reference ON (amir_effective_reference.chg = amir_effective_change.chg)
SET amir_effective_change.effective = NULL
WHERE amir_effective_change.rltn IN (100);
SELECT * FROM amir_effective_change;
+------+------+------+-------+-----------+
| chg | txn | rltn | entry | effective |
+------+------+------+-------+-----------+
| 10 | 100 | 100 | 500 | NULL |
+------+------+------+-------+-----------+
1 row in set (0.00 sec)