如何在删除另一个 table 中的行之前检查现有行?
How to check existing row before deleting row in another table?
我有两个表:
// table1 // table2
+----+------+---------+ +----+------+
| id | col1 | user_id | | id | col2 |
+----+------+---------+ +----+------+
| 1 | a | 100001 | | 1 | a |
| 2 | b | 100002 | | 2 | b |
| 3 | c | 100003 | | 3 | c |
+----+------+---------+ | 4 | a |
| 5 | a |
| 6 | c |
+----+------+
我还有一个名为 $user_id
的变量。现在我想删除 table2
中 col2='a'
中的所有行,但我需要在删除之前检查 table1
中的 table1.user_id = $user_id
(在本例中为 $user_id = '100001'
) .
如何使用此概念编写正确的语法查询:
IF table1.user_id = $user_id where table1.col1 = 'a' then
delete from table2 where col2 = 'a'
我可以使用 PHP 和 MySQL 使用两个单独的查询来做到这一点。但是我想通过一个查询来做到这一点,这可能吗?
您可以使用 JOIN 来执行删除操作
delete t2 from table2 t2
join table1 t1 on t2.col2 = t1.col1
where
t2.col2 = 'a'
and t1.user_id = '100001'
我有两个表:
// table1 // table2
+----+------+---------+ +----+------+
| id | col1 | user_id | | id | col2 |
+----+------+---------+ +----+------+
| 1 | a | 100001 | | 1 | a |
| 2 | b | 100002 | | 2 | b |
| 3 | c | 100003 | | 3 | c |
+----+------+---------+ | 4 | a |
| 5 | a |
| 6 | c |
+----+------+
我还有一个名为 $user_id
的变量。现在我想删除 table2
中 col2='a'
中的所有行,但我需要在删除之前检查 table1
中的 table1.user_id = $user_id
(在本例中为 $user_id = '100001'
) .
如何使用此概念编写正确的语法查询:
IF table1.user_id = $user_id where table1.col1 = 'a' then
delete from table2 where col2 = 'a'
我可以使用 PHP 和 MySQL 使用两个单独的查询来做到这一点。但是我想通过一个查询来做到这一点,这可能吗?
您可以使用 JOIN 来执行删除操作
delete t2 from table2 t2
join table1 t1 on t2.col2 = t1.col1
where
t2.col2 = 'a'
and t1.user_id = '100001'