CREATETABLEIFNOTEXISTS exam (
id int(11)NOTNULLPRIMARYKEYAUTO_INCREMENT,
name varchar(50)NOTNULL,
chinese doubleDEFAULTNULL,
math doubleDEFAULTNULL,
english doubleDEFAULTNULL);INSERTINTO exam (id, name, chinese, math, english)VALUES(1,'谢逊',99,70,80),(2,'张无忌',80,95,78),(3,'周芷若',85,NULL,91),(4,'张三丰',88,73,78);CREATETABLEIFNOTEXISTS orders (
id int(11)DEFAULTNULL,
product varchar(50)DEFAULTNULL,
price floatDEFAULTNULL);INSERTINTO orders (id, product, price)VALUES(1,'电视',1500),(2,'冰箱',900),(3,'洗衣机',1300),(4,'空调',2200),(5,'电风扇',180);CREATETABLEIFNOTEXISTSuser(
id int(11)DEFAULTNULL,
name varchar(50)DEFAULTNULL,
age int(11)DEFAULTNULL);INSERTINTOuser(id, name, age)VALUES(1,'谢逊',59),(2,'张无忌',21),(3,'周芷若',18),(4,'张三丰',65),(5,'赵敏',19),(6,'杨遥',27);
基础查询
查询表中所有学生的信息
select id,name,chiese,math,english from exam;select*from exam;
select
name as 姓名,
ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)as 总分
from exam;select
name 姓名,
ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0) 总分
from exam;
条件查询
查询姓名为谢逊的学生成绩
select name,math,chinese,english from exam where name='谢逊';
查询英语成绩大于80分的同学
select name,english from exam where english>80;
查询总分大于250分的同学
select
name,
ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)as fen
from exam
where ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)>250;
查询数学分数在 80-100之间的同学
select name,math from exam where chinese>80and chinese<100;select name,math from exam where chinese between80and100;
查询语文分数为85-88的同学,再查询分数不在这个范围内的同学
select name,chinese from exam where chinese=85or chinese=86or chinese=87or chinese=88;select name,chinese from exam where chinese!=85and chinese!=86and chinese!=87and chinese!=88;select name,chinese from exam where chinese in(85,86,87,88);select name,chinese from exam where chinese notin(85,86,87,88);
查询所有姓张的学生成绩
select*from exam where name like'张%';
查询英语分>70,语文分>80 且数学成绩为null的同学
select*from exam
where english>70and chinese>80and math isnull;
对英语成绩降序输出
select*from exam orderby english desc;
对姓张的学生总分升序输出
select
name,ifnull(math,0)+ifnull(chinese,0)+ifnull(english,0)as fen
from exam
where name like'张%'orderby fen asc;