2

I would like to delete set of rows, which have same property like this SQL select.

SELECT item_id, count(*) as item_in_order
FROM items
GROUP BY order_id
HAVING item_in_order = 1

In words it means, that I have items of orders and I would like to delete rows, which are from orders with only one Item.

For example:

item_id    order_id
1          1
2          2
3          2
4          3
5          3
6          4

So I would like to delete rows with item_id 1 and 6.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1336101
  • 441
  • 1
  • 7
  • 17

1 Answers1

5

you can use this query

delete from items
where order_id in 
   (SELECT order_id
    FROM items
    GROUP BY order_id
    HAVING count(*)  = 1
   )

it will delete the row where order_id exist only once in items table

Deepak Sharma
  • 4,124
  • 1
  • 14
  • 31
  • 2
    Looks clear, I tried exactly this same but result is error: eror in query (1093): You can't specify target table 'items' for update in FROM clause – user1336101 Jan 29 '14 at 14:55
  • Yes I use. Is possible delete from same query that I select? I do not understant it. I think it is similar like this http://stackoverflow.com/questions/45494/mysql-error-1093-cant-specify-target-table-for-update-in-from-clause – user1336101 Jan 29 '14 at 15:04
  • hey dont mind but for time being u can try by duplicating this table and after deleting the record just delete the duplicate table.. does it make any sense?? – Deepak Sharma Jan 29 '14 at 15:12