根据其他表中的值删除表中的行

时间:2014-12-05 20:19:54

标签: mysql

我有一个像这样的简化表(table1):

id | note
----------------------------------
 1 | some note
 2 | some note
 3 | another note
 4 | some note

和另一个(table2):

id | note
----------------------------------
 1 | some note
 2 | another note
 3 | some note
 4 | another note

根据table1中的id,我想删除table2中的行,其中table1.note等于table2.note。

如果我提供tabel1的id = 3,则应删除table2的id为2和4的行。

我试过了:

DELETE FROM table2
JOIN table1 WHERE id = ?
WHERE table1.note = table2.note

但我得到的是“ER_PARSE_ERROR”。

正确的mysql语法是什么?

2 个答案:

答案 0 :(得分:2)

您可以如下编写查询,只能指定一次WHERE子句而不是ON子句来完成您的加入部分,或者您可以在AND之后使用WHERE更多条件

DELETE t2.*
FROM
  table2 t2
  JOIN table1  t1
ON t1.note = t2.note 
WHERE t1.id = 3 

答案 1 :(得分:2)

您可以在join语句中的table1和table2之间执行delete

DELETE T2 FROM Table2 T2
JOIN Table1 T1
ON T1.note = T2.note
AND T1.id =3