views:

236

answers:

3

I have a table taged with two fields sesskey (varchar32 , index) and products (int11), now I have to delete all rows that having group by sesskey count(*) = 1. I'm trying a fews methods but all fails.

Example: delete from taged where sesskey in (select sesskey from taged group by sesskey having count(*) = 1)

The sesskey field could not be a primary key because its repeated.

+1  A: 
Charles Bretana
Won't work (+15 chars)
Quassnoi
#1093 - You can't specify target table 'taged' for update in FROM clause
Alex
That error is confusing... There's no "Update" going on here... What is it referring to ? The use of the tablename oin the Delet clause? or the use of the tablename in the subquery (which is neither Updating nor deleting anything)
Charles Bretana
`MySQL` does not support target tables in the correlated subqueries (be it `DELETE` or `UPDATE`). Yes, the error is confusing.
Quassnoi
@Quassnoi, Thx, I did not know this.. Do not use MySQL, but I will remember this... I bet (assume) this rule also applies to Updates which have subqueries in the Where clause - (I'm going to take a wild stab and guess that's what the error message was actually drafted for...) ?
Charles Bretana
`@Charles`: sure, that is what it was intended for.
Quassnoi
+1  A: 

Or if you're using an older (pre 4.1) version of MySQL and don't have access to subqueries you need to select your data into a table, then join that table with the original:

CREATE TABLE delete_me_table (sesskey varchar32, cur_total int);

INSERT INTO delete_me_table SELECT sesskey, count(*) as cur_total FROM orig_table
WHERE cur_total = 1 GROUP BY sesskey;

DELETE FROM orig_table INNER JOIN delete_me_table USING (sesskey);

Now you have a table left over named delete_me_table which contains a history of all the rows you deleted. You can use this for archiving, trending, other fun and unusual things to surprise yourself with.

coffeepac
+1  A: 
DELETE  si
FROM    t_session si
JOIN    (
        SELECT  sesskey
        FROM    t_session so
        GROUP BY
                sesskey
        HAVING  COUNT(*) = 1
        ) q
ON      q.sesskey = si.sesskey

You need to have a join here. Using a correlated subquery won't work.

See this article in my blog for more detail:

Quassnoi
Perfect!!!!! Thank you very much. And the article very usefull.
Alex