MySQL的一些基本操作总结了一部分(通过自己创建的一个表)

mysql的一些常用查询的记录:
(本例中用的是本人mysql数据库中创建的student表,其属性如下:
   id(编号)(id 主键),name(姓名),sex(性别),goal(分数),birthday(生日),tid(教师编号(作为外键存在))  
1.将日期转换成指定的格式查询
 select name, date_format(birthday,'%Y-%m-%d') 年份 from student;
 select str_to_date(birthday,'%Y-%m-%d')年份 from student;
2.查询星期几
 select dayofweek(now());//当前是星期几
 select dayofweek(birthday) from student;//查询表中时间是星期几
3.查询是表中的天数,月份,年份
 select date_format(birthday,'%d') from student;
 select date_format(birthday,'%m') from student;
 select date_format(birthday,'%Y') from student;
4. nvl 相似用法ifnull; expr1为空则用expr2的值
  IFNULL()返回一个数字或字符串值,取决于它被使用的上下文环境
  select ifnull(expr1,expr2) from tableName;
  coalesce(expr1,expr2,expr3......exprn)表示函数返回第一个
  非空表达式
   select coalesce(null,null,birthday) from student;
   >birthday信息;
5. 聚合函数的用法,以及groupby子句的用法,查询表中分数最高,最低,平均分,总分
   以及按每个tid分组的总人数,tid   (按照tid分组)
   a.select min(goal),max(goal),sum(goal),avg(goal),count(id),tid from 
   student group by tid having count(tid)>3;
   b.select min(goal),max(goal), sum(goal),avg(goal),count(id),tid from 
   student where count(tid)>3 group by tid;
   b的性能远远高于a的性能;
   优先级:from --->1
           where --->2
           group by--->3
           having --->4
           select --->5
           order by--->6
6.查询出生在二月学生信息(两种查询方式一模一样,只是函数调用方法不同);
  (1).select id,name,sex,date_format(birthday,'%Y-%m-%d') 出生年月,goal from   student where birthday like'%-02-%';
  (2).select id,name,sex,birthday, goal from student where date_format(birthday,'%m')='02';
7.查询每个学生的年龄(每个学生从出生到现在来到这个世界上有多少天);
  下面的curdate()也可以用now(),sysdate()这两个函数代替
  select id,name,sex, goal,round(datediff(curdate(),birthday)/365) 年龄 from   student ;
8.查询每个学生的编号,姓名,性别,分数,(现在教育改革,分数每人都加上5分 )  Newgoal ;如果写成New Goal 要加上双引号或者单引号
  select id,name,sex,goal,goal+5 Newgoal from student;
  select id,name,sex,goal,goal+5 "New Goal" from student;
  select id,name,sex,goal,goal+5 'New Goal' from student;
9.加入现在每个人六个月后都发生了一件不寻常的事情,那么现在请用函数
  查询出每个学生这一天的相关信息(id,name,sex,birthday,New Day)
  select id,name,sex,birthday,date_add(birthday,interval 6 month) "New Day"   from student;
10. 查询学生姓名不为空的学生总数  *可以替换成id,name,birthday,sex,tid,goal都可
    select count(*) from student where name is not null;
11. 查询学生中老师个数,也就是tid总数(不带重复的)
    select count(distinct tid) TN from student;
12. 查询每个老师带的学生里面最高分,最低分学生的信息
    select tid, max(goal),min(goal) from student group by tid;
13. 查询教师编号为T01的学生总数
    select count(tid)from student where tid='T01';
14. 显示老师编号,以及老师给该编号下学生的最低分数,排除最低分数小于70的,按分数高低降序输出
    select tid,min(goal) from student group by tid having min(goal)>70 order by min(goal) desc;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值