MySQL查询数据(超详细)
一、简单查询语句
select * from 表名 条件查询语句;
二、多表查询
多张表有同名字段出现在select语句中,同名字段必须带上 “表名 . 字段名”
同名字段必须带上表名
如:
select xxb1.学号,姓名,分数 from xxb1 a,cjb b where a.学号=b.学号;
内连接:
1.使用=符号
2.使用inner join…on…
3.使用join…on…
如:
select * from emp,dept where Dept_id=dept.id;
select * from emp join dept on Dept_id=dept.id;
select * from emp inner join dept on Dept_id=dept.id;
自身连接:
一个表与其自己进行连接;需要给表起别名以示区别
如:
select Qir.cno,Qir.cname, Qir.cpno,sec.cname from course Qir,course sec where Qir.cpno=sec.cno
外连接:
可以左向外连接、右向外连接,外连接是以左边或右边的表作为主表,把主表的内容都显示,从表没有的内容置为空处理
例如:主表 left join 表 ON a.no=b.no; 也可以换成left join
代码如下:
select s.sno,sname,sex,age,dept,cno,grade from student s left join sc ON s.sno=sc.sno
左连接:left join
右连接:right join
三、嵌套查询、子查询
from使用子查询:对数据来源的二次加工
如:
select * from xxb1 as a,(select max(语文) as x from cjb) as b where a."学号"=b.x;
在where中使用子查询
如:
select * from score where score=(select max(secre) from score);
在select中使用子查询
如:
select (select count(*) from score where score'09:00')/(select count(*) from kq);
嵌套查询
如:
select 字段 from 表名 where 条件 group by 分组 having 聚合函数的条件语句 order by 排序子句
四、case语句
用法1:case 表达式
when 值1 then 返回值
when 值2 then 返回值
…
end
说明:end表示结束,也可以加上else ‘默认值’
如:
select no,bir,
(case year(bir)
when '1998' then '小鲜肉'
when '1997' then '鲜肉'
when '1996' then '肉'
else '腊肉'
end) 个性化标志
from stu;
用法2:case
when 表达式 运算符 值1 then 返回值1
when 表达式 运算符 值1 then 返回值2
…
else 返回值
end
如:
select
(case
when year(bir)>'1999' then '小鲜肉'
when year(bir)>='1995' and year (bir)='1990' and year (bir)=60 and result=70 and result=80 and result=90 then '90以上'
else '不及格'
end) 分数段
from grade) a
group by a.分数段;
