Php 如何在删除其他表中的行之前检查现有行?
我有两张桌子:Php 如何在删除其他表中的行之前检查现有行?,php,mysql,sql-delete,Php,Mysql,Sql Delete,我有两张桌子: // table1 // table2 +----+------+---------+ +----+------+ | id | col1 | user_id | | id | col2 | +----+------+---------+ +----+------+ | 1 | a | 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\u id的变量。现在我想删除表2中col2='a'的所有行,但我需要检查表1.user\u id=$user\u id,在本例中,删除前先检查表1中的$user\u 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'
啊,但是你能告诉我你的查询会删除哪些行吗?!只有表2中col2='a'的所有行?查询逻辑是通过将表1的col2与col1连接起来,从表中查找行,然后检查col2='a'和表1用户id是否是给定的输入。因此,它必须将记录与指定的条件匹配,然后从表2中删除。看,您的解决方案很好,但因为我使用触发器,join和delete中存在冲突,在这种情况下我不能使用join。所以我想知道,如果此条件为真,有一种使用方法:从表1中选择ExistSelect1,其中user_id='100001'LIMIT 1,然后运行DELETE query?否您不能在查询中使用IF-else,除非查询是触发器或存储过程的一部分。