mysql-常用sql语句
1,排序
a,单列排序:select * from table_name order by column_name DESC (注:order by 后不写默认asc升序,desc降序)
b,多列排序:select * from table_name order by column_name1, column_name2 DESC (注:先根据column_name1进行排序,若column_name1相等则根据column_name2进行排序)
c,其它条件排序:
select * from table_name order by column_name1<NOW(), IF(
column_name1<NOW(),
0,
column_name1
),
column_name1 DESC
(注:先按大于当前时间升序排,再按小于当前时间降序排)
d,指定字段排序
select * from table_name order by column_name1 ASC,column_name2 DESC (注:先根据column_name1升序排,再根据column_name2降序排)
2,聚合
a,count()数据库表总行数
select count(*) from t_city
b,sum(),数据表某列求和
select sum(column_name1) from t_city
c,max(),数据表某列最大值
select max(column_name1) from t_city
d,min(),数据表某列最小值
select min(column_name1) from t_city
e,avg(),数据表某列平均值
select avg(column_name1) from t_city
f,group by,聚合
查询出每个科目下最高分成绩的学生信息,显示学生的所有信息字段
先根据科目聚合查出每个科目中最高分数,因为要显示学生的所有字段,则此处将聚合查出的数据作为一张表,再联合学生表再次进行数据过滤
select t1.* from sdutent as t1,(
select dept,max(score)as score2 from student GROUP BY dept) as t2
where t1.dept=t2.dept and t1.score=t2.score2
若需要再增加过滤条件,查询出每个科目下最高分数且是女生的学生信息
select t1.* from sdutent as t1,(
select dept,max(score)as score2 from student GROUP BY dept having sex='女') as t2
where t1.dept=t2.dept and t1.score=t2.score2
3,查询前N条数据
a,select * from t_test1 limit 1(查询第一条数据)
b,select * from t_test1 limit 1,5(即从第二行开始查询五条数据,查询的2-6行的数据)
c,select * from t_test1 limit 0,5或select * from t_test1 limit 5(查询前N条数据)
4,查询一周内数据,一年数据,N天的数据
NOW() 函数:显示年月日时分秒2020-05-09 16:53:01
CURDATE() 函数:显示年月日2020-05-09
CURTIME() 函数:显示时分秒16:53:01
a)查询当天数据
select * from t_city where TO_DAYS(create_time)=TO_DAYS(NOW())
b)查询昨天数据
select * from t_city where (TO_DAYS(NOW())-TO_DAYS(create_time))<=1
c)查询7天前的数据
select * from t_city where DATE(create_time)< DATE_SUB(NOW(),INTERVAL 7 DAY)
d)查询当前时间往前推7天内的数据
select * from t_city where DATE(create_time)>= DATE_SUB(CURDATE(),INTERVAL 7 DAY) and DATE(create_time) <=DATE_FORMAT(NOW(),'%Y-%m-%d')
e)查询当前月的数据
select * from t_city where DATE_FORMAT(create_time,'%Y-%m')=DATE_FORMAT(CURDATE(),'%Y-%m')
5,去重复
单字段重复记录
查询出城市名称相同的记录
步骤1:先查出重复项
select city from t_test4 group by city having count(*)>1
步骤2:再查询出重复项的整条数据
select * from t_test4 where city in(
select city from t_test4 group by city having count(*)>1)
使用distinct去重复,但distinct只能返回目标字段,无法返回其它字段
select distinct city from t_test4
6,多表联合查询
多表联合查询包含四种查询方法
a)最常见的一种:select * from t_test1,t_test2 where t_test1.id=t_test2.t_id (注:两表中有匹配的就返回)
b)inner join内连接 select * from t_test1 inner join t_test2 on t_test1.id=t_test2.t_id (注:两表中有匹配的就返回)
c)left join 左连接 select * from t_test1 left join t_test2 on t_test1.id=t_test2.t_id (注:以左表为主表,返回左表所有数据及右表匹配的数据)
d)right join 右连接 select * from t_test1 right join t_test2 on t_test1.id=t_test2.t_id (注:以右表为主表,返回右表所有数据及左表匹配的数据)