09-10:Where,Having与连接

2018-09-10  本文已影响0人  神坛下的我

概念要达到默写的程度。

where 谓语查询 条件查询

范围

between and 包含边界值

列表

模糊查询 正则表达式

select name,homephone from student where homephone regexp('139[0-9]{8}')
select '移动号码',count(*) from student where homephone regexp('13[4-9][0-9]{8}')
union
select '联通号码',count(*) from student where homephone regexp('13[0-3][0-9]{8}')
union
select '电信号码',count(*) from student where homephone regexp('18[0-9][0-9]{8}')

having 分组结果查询


Example

SELECT NAME,FLOOR(FLOOR(TIMESTAMPDIFF(DAY,jointime,NOW())/365)) AS '工龄',
FLOOR(FLOOR(TIMESTAMPDIFF(DAY,brithday,jointime)/365)) AS '参加工作年龄' FROM employee 
WHERE FLOOR(FLOOR(TIMESTAMPDIFF(DAY,jointime,NOW())/365)) >=10
select did,concat(floor(timestampdiff(YEAR,jointime,now())/3)*3,'-',floor(timestampdiff(YEAR,jointime,now())/3)*3+2) 
as '工龄段' from employee 
group by did,floor(timestampdiff(YEAR,jointime,now())/3) 

连接

有条件连接 和 无条件连接(笛卡尔积-排列组合)

eg1:select * from student,class
eg2:select * from student cross join class 
eg1:select * from student s join class c on s.cno = c.cno(等值连接)
eg2:select t.tno,count(cno) from teacher t left outer join class c on t.tno = c.tno group by t.tno

eg3:统计各位同学报道注册的次数
SELECT s.`name` AS '姓名',COUNT(SRID) AS '报道注册次数' FROM student s LEFT OUTER JOIN studentreg st ON s.`sno` = st.`sno` GROUP BY s.`sno`

eg1:统计各位教师所带的学生人数

select t.tno,t.tname,count(s.sno) from teacher t left join class c on t.tno = c.tno 
left join student s on c.cno = s.cno 
group by t.tno,t.tname having count(s.sno) <= 2

eg2:统计各门课程选课的男女人数

SELECT c.cno,c.cname,s.sno,sex,COUNT(s.sno) FROM course c JOIN sc ON c.cno = sc.cno 
JOIN student s ON sc.sno = s.sno 
GROUP BY c.cno,c.cname,sex

eg3:统计各个技能男女生人数

select s.sid,s.name,e.sex,count(e.eid) from skill s join es on s.sid = es.sid join employee e on e.eid = es.eid 
group by s.sid,s.name,e.sex
select s1.name,s1.sex,s2.name,s2.sex from student s1 join student s2 on s1.area = s2.area 
where s1.sno <> s2.sno
效率优化:
select s1.name,s1.sex,s2.name,s2.sex from student s1 join student s2 on s1.area = s2.area 
and s1.sno <> s2.sno
select mgirl.mname,mgirl.msex,timestampdiff(YEAR,mgirl.birthday,now()) as '女方年龄',mboy.mname,
mboy.msex,timestampdiff(YEAR,mgirl.birthday,now()) as '男方年龄' 
from memberinfo mboy join memberinfo mgirl 
where mboy.msex = '男' and mgirl.msex='女' and mboy.high - mgirl.high between 0 and 10 
and abs(timestampdiff(YEAR,mboy.birthday,mgirl.birthday)) <10 
and (if(mgirl.o1 - mboy.y1 > 0,1,0) + if(mgirl.o2 - mboy.y2 > 0,1,0) + if(mgirl.o3 - mboy.y3 > 0,1,0) + 
if(mgirl.o4 - mboy.y5 > 0,1,0)) > =2 and (if(mboy.o1 - mgirl.y1 > 0,1,0) + if(mboy.o2 - mgirl.y2 > 0,1,0) + 
if(mboy.o3 - mgirl.y3 > 0,1,0) +if(mboy.o4 - mgirl.y4 > 0,1,0) +) >=3 
上一篇下一篇

猜你喜欢

热点阅读