如果两列相等,MySQL查询删除行

时间:2014-06-27 13:10:33

标签: php mysql

如果两列的值相等,则如何从mysql表中删除所有行

示例表

invoice_id| item_id | name  | invoiced_qty | received_qty
---------------------------------------------------------
|  1      |  1      | item1 |   3          |     2    
|  2      |  2      | item2 |   5          |     5   
|  3      |  1      | item3 |   4          |     3   
|  4      |  2      | item4 |   2          |     2   
|  5      |  1      | item5 |   5          |     5

删除表后需要保留

invoice_id| item_id | name  | invoiced_qty | received_qty
---------------------------------------------------------
|  1      |  1      | item1 |   3          |     2    
|  3      |  1      | item3 |   4          |     3   

我创建的选择查询是

SELECT * FROM table1 A 
INNER JOIN table1 B ON A.item_id = B.item_id 
AND A.invoice_id = B.invoice_id
AND A.invoiced_qty = B.received_qty

由于

3 个答案:

答案 0 :(得分:5)

为什么不只是SQL Fiddle

DELETE FROM table1 
WHERE invoiced_qty = received_qty

您的修改不会改变任何内容。他是SQL Fiddle演示您的SELECT查询。根据您的示例数据,A.invoice_id永远不会等于B.invoice_id。所以你不会得到任何结果。

答案 1 :(得分:0)

您可以简单地包装您的select语句并选择要通过id删除的值,如下所示:

DELETE FROM table1 
WHERE item_id  IN (SELECT item_id FROM table1 A 
INNER JOIN table1 B ON A.item_id = B.item_id 
AND A.invoice_id = B.invoice_id
AND A.invoiced_qty = B.received_qty)

然而你应该接受Linger的答案,因为它是更直接的解决方案,我的目的是表明如果你选择了一些东西,通常可以包装和删除。

答案 2 :(得分:0)

试试这个:

DELETE FROM table1 A
INNER JOIN table1 B ON A.item_id = B.item_id 
WHERE A.invoiced_qty = B.received_qty