数据库常用操作整理

例子一:

在数据库中往往有以下的统计操作,要统计某种类型的样本有多少个,并且找出大于500个样本的类型,以及拥有的样本数目。具体例子如,在SQL中,一个表的定义如下:

CREATE TABLE t_account(
     account varchar(100),
     account_type TINYTEXT,
     PRIMARY KEY (account),
};

account为账号,account_type为该账号的类型,写出一个sql,统计账号数累计超过5000个账号类型,并显示对应的账号数,即结果中每行是(账号类型,账号数)

select account_type, count(account) from t_account group by account_type having count(account)>5000;

例子二:(Leetcode196: Delete Duplicate Emails)

Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id is the primary key column for this table.

For example, after running your query, the above Person table should have the following rows:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

找到要保留的数据 然后用not in 来删除不再这些数据中的记录。大家很容易就想到如下的sql语句:

delete from Person where Id not in (select * from (select min(Id) from Person group by Email));

  但是mysql删  除动作不能带有本表的查询动作,意思是你删除users表的东西不能以Person表的信息为条件 所以这个语句会报错,执行不了。只要通过创建临时表作为查询条件。具体实现如下:

delete from Person where Id not in (select * from (select min(Id) from Person group by Email) as w);

  

posted @ 2015-04-24 15:46  SevenForever  阅读(430)  评论(0编辑  收藏  举报