2

How to delete all rows from a mysql table if values of two columns are equal

Example Table

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

After deleting table needs to retains

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

The select query which i created is

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

Thanks

3 Answers 3

5

Why not just SQL Fiddle:

DELETE FROM table1 
WHERE invoiced_qty = received_qty

Your edit does not change anything. He is the SQL Fiddle demonstrating your SELECT query. According to your sample data A.invoice_id will never equal B.invoice_id. So you will not get any results.

3
  • was about to post that :P
    – NeeL
    Jun 27, 2014 at 13:15
  • i need to check the invoice_id and item_id also. same item_id, same invoice_id and equal qty Jun 27, 2014 at 13:32
  • You are never going to have the same invoice_id in multiple records according to the sample data you provided. It looks like your invoice_id is unique. So there is no point in joining the table to itself.
    – Linger
    Jun 27, 2014 at 13:39
0

Try this :

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

You could simply wrap your select statement and select values to be deleted by id, like this:

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)

however you should accept answer by Linger as it is more straightforward solution, mine was to indicate that if you have something selected usually you can wrap and delete.

1
  • Sorry I forget to add one more column. There is a invoice_id also. I need to check both invoice_id and item_id. Jun 27, 2014 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.