MYSQL delete all results having count(*)=1

回眸只為那壹抹淺笑 提交于 2019-12-29 04:24:08

问题


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:


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:

  • Keeping rows



回答2:


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.




回答3:


The SubQuery should work

 Delete from taged 
  Where sesskey in 
     (Select sesskey 
      From taged 
      Group by sesskey 
      Having count(*) = 1)

EDIT: Thanks to @Quassnoi comment below... The above will NOT work in MySql, as MySql restricts referencing the table being updated or deleted from, in a Subquery i you must do the same thing using a Join ...



来源:https://stackoverflow.com/questions/1902014/mysql-delete-all-results-having-count-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!