记录下工作中常用的sql
删除重复数据
delete from student where id not in (select min(id) from student group by name);
-- 该语句在mysql下会报错,
-- 执行报错:1093 - You can't specify target table 'student' for update in FROM clause
-- 原因是:更新数据时使用了查询,而查询的数据又做了更新的条件,mysql不支持这种方式。外边在包一层即可
delete from student where id not in (select minid from (select min(id) as minid from student group by name) b);
查找全部重复记录
SELECT * FROM t_info a WHERE ((SELECT COUNT(*) FROM t_info WHERE Title = a.Title) > 1) -- 重复标题
每组的前N条数据
-- 对上面数据按照日期分组,每组取qty_ordered最大的前5条
SELECT * FROM 表名 a WHERE (SELECT count(*) FROM 表名 b WHERE b.日期=a.日期 AND b.id>a.id )<5;
分组的,某个字段最大
select a.* from table2 as a where age = (select max(age) from table2 where a.table1_id=table1_id);
条件总数
select
COUNT(1),
COUNT(IF(source = 2 OR source =3 ,TRUE,NULL)) AS zq,
COUNT(IF(source =1,TRUE,NULL))AS jdcount
from table
其他
SELECT SEC_TO_TIME (89 53);
select md5();
select day(now());
DATE_FORMAT( deteline, "%Y-%m-%d %H" );
CONVERT(FROM_BASE64(content),CHAR);
weight + 120 - FLOOR(TIMESTAMPDIFF(DAY,create_time,NOW())/30)*10