码迷,mamicode.com
首页 > 数据库 > 详细

MySQL基本语句与经典习题

时间:2018-03-26 19:16:43      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:多表连接   sts   大全   set   教师   any   单位   9.png   求和   

SQL语句大全

本文用到的数据(5张表):

customers:

技术分享图片

orders:

技术分享图片

orderitems:

技术分享图片

Products:

技术分享图片

 Vendors:

技术分享图片

一、检索数据-select语句
select prod_name from products;                        #检索单个列
select prod_id,prod_name,prod_price from products;         #检索多个列
select * from products;#检索所有列
select distinct vend_id from products;                 #选择不同的值,注意distinct作用于所有列而不仅是紧跟在其后的一列

select prod_name from products
limit 5;#返回5行

select prod_name from products
limit 5 offset 5;                                                     #返回从第5行起的5行数据:limit 开始 offset 行数

二、注释
行内注释:--注释
行内注释:#注释
多行注释:/*注释*/

三、排序检索数据
select prod_name from products
order by prod_name;                                             #按单列排序

select prod_id,prod_price,prod_name from products
order by prod_price,prod_name;                           #按多个列排序,首先对price排,再对name排,注意仅在多行具有相同的price时才会对name进行排序

select prod_id,prod_price,prod_name from products
order by prod_price desc,prod_name;                   #对price降序,name升序,注意desc只应用到直接位于其前面的列名

四、过滤数据-where子句
select prod_name,prod_price from products
where prod_price<10;                                            #检查单个值

where vend_id <>‘DLL01‘;                                     #不匹配检查
where vend_id !=‘DLL01‘;

select prod_name,prod_price from products
where prod_price between 5 and 10;                     #范围性检查

select prod_name from products
where prod_price is null;                                         #检查空值

select prod_id,prod_price,prod_name from products
where vend_id=‘DLL01‘ and prod_price<=4;          #and操作符

where vend_id=‘DLL01‘ or vend_id=‘BRS01‘;        #or操作符

where vend_id in(‘DLL01‘,‘BRS01‘);                      #in操作符,与or等价

where not vend_id=‘DLL01‘;                                  #not操作符,否定跟在其后的条件,等价于:where vend_id <>‘DLL01‘

where prod_name like ‘Fish%‘;                             #like操作符+%通配符,返回所有以Fish起头的产品

where prod_name like‘%bean bag%‘;                  #检索包含文本bean bag的值,不管在之前还是之后。

where prod_name like‘F%y‘;                                #检索以F起头,以y结尾的所有产品

五、汇总数据
select avg(prod_price) as avg_price                     #avg()用于求均值,只用于单列,忽略列值为null的行
from products;

select count(*) as num_cust from customers;      #计算表中行的数目,不忽略空值

select count(cust_email) as num_cust                 #计算指定列中具有值的行数,掠过空值
from customers;

select max(prod_price) as max_price                #返回最大价格,忽略空值
from products;

select min(prod_price) as min_price                  #返回最低价格,忽略空值
from products;

select sum(quantity) as items_ordered                #求和,忽略空值
from orderitems;

六、分组数据
select vend_id,count(*) as num_prods
from products
group by vend_id;                                                #按id进行分组,count对每个id都做一次计数,group by子句必须出现在where子句之后,order by之前

group by cust_id
having count(*)>=2;#过滤分组

七、子查询
select cust_id from orders
where order_num in(select order_num from orderitems
                   where prod_id=‘RGAN01‘);               #由内向外执行
等价于:
select order_num from orderitems
where prod_id=‘RGAN01‘;

输出:
order_num
-------------
20007
20008

select cust_id from orders
where order_num in(20007,20008);

八、联结表
#内连接(等值连接)
select vend_name,prod_name,prod_price
from vendors inner join products
on vendors.vend_id=products.vend_id;            #连接条件为vendors.vend_id=products.vend_id
等价于:
select vend_name,prod_name,prod_price
from vendors,products
where vendors.vend_id=products.vend_id;

#多表连接
select prod_name,vend_name,prod_price,quantity
from oederitems,products,vendors
where products.vend_id=vendors.vend_id
and orderitems.prod_id=products.prod_id
and order_num=20007;

#自连接
select c1.cust_id,c1.cust_name,c1.cust_contact
from customers as c1,customers as c2              #使用表别名
where c1.cust_name=c2.cust_name
and c2.cust_contact=‘jim jones‘;
等价于:
select cust_id,cust_name,cust_contact
from customers
where cust_name=(select cust_name
                 from customers
                 where cust_contact=‘jim jones‘);

#外连接
select customers.cust_id,orders.order_num
from customers left outer join orders
on customers.cust_id=orders.cust_id;                 #左外连接,left指定from子句左边的表(customers)选择所有行
输出:

技术分享图片

select customers.cust_id,orders.order_num
from customers right outer join orders
on customers.cust_id=orders.cust_id;                 #右外连接,right指定from子句右边的表(orders)选择所有行
输出:

技术分享图片

九、组合查询
#union:组合多个查询的结果到一个输出集,所以要求union中每个查询必须包含相同的列,表达式或聚合函数

select cust_name,cust_contact,cust_email
from customers
where cust_state in(‘il‘,‘in‘,‘mi‘);#查询一
输出

技术分享图片

select cust_name,cust_contact,cust_email
from customers
where cust_name=‘fun4all‘;#查询二
输出:

技术分享图片

select cust_name,cust_contact,cust_email
from customers
where cust_state in(‘il‘,‘in‘,‘mi‘)
union
select cust_name,cust_contact,cust_email
from customers
where cust_name=‘fun4all‘;                        #组合查询,默认去除重复行,使用union all则返回所有匹配行
输出

技术分享图片

十、更新和删除数据
#update
update customers                                    #指定要更新的表
set cust_email=‘kim@thetoystore.com‘   #指定列名和其新值
where cust_id=‘1000000005‘;                  #确定要更新哪些行的过滤条件

update customers
set cust_contact=‘sam roberts‘,
    cust_email=‘sam@toyland.com‘
where cust_id=‘1000000006‘;                 #更新多个列时,中间用,隔开

update customers
set cust_email=null
where cust_id=‘1000000005‘;                #相当于删除作用

#delete
delete from customers
where cust_id=‘1000000006‘;

SQL经典练习

/*--------------创建并使用数据库------------*/
mysql> create database 50q;
mysql> use 50q;

/*-------------------建表-------------------------*/
mysql> CREATE TABLE STUDENT 

 SNO       VARCHAR(3) NOT NULL,  
 SNAME     VARCHAR(4) NOT NULL, 
 SSEX      VARCHAR(2) NOT NULL,  
 SBIRTHDAY DATETIME, 
 CLASS     VARCHAR(5) 
 );

mysql> CREATE TABLE COURSE 

 CNO   VARCHAR(5)  NOT NULL,  
 CNAME VARCHAR(10) NOT NULL,  
 TNO   VARCHAR(3) NOT NULL 
 );

mysql>  CREATE TABLE SCORE  

 SNO    VARCHAR(3)     NOT NULL,  
 CNO    VARCHAR(5)     NOT NULL,  
 DEGREE NUMERIC(10, 1) NOT NULL 
 ) ; 

mysql>  CREATE TABLE TEACHER  

 TNO       VARCHAR(3)  NOT NULL,  
 TNAME     VARCHAR(4)  NOT NULL,  
 TSEX      VARCHAR(2)  NOT NULL,  
 TBIRTHDAY DATETIME    NOT NULL,  
 PROF      VARCHAR(6),  
 DEPART    VARCHAR(10) NOT NULL 
 );

/*---------------添加主键--------------*/
mysql>  ALTER TABLE STUDENT ADD PRIMARY KEY (SNO);
 ALTER TABLE SCORE   ADD PRIMARY KEY (SNO,CNO); 
 ALTER TABLE COURSE  ADD PRIMARY KEY (CNO); 
 ALTER TABLE TEACHER ADD PRIMARY KEY (TNO);

#--------主键在两张table中的数据类型须一致-------*/

mysql>  ALTER TABLE SCORE   ADD CONSTRAINT FK_SCORE_STUDENT  FOREIGN KEY (SNO) REFERENCES STUDENT(SNO); 
 ALTER TABLE SCORE   ADD CONSTRAINT FK_SCORE_COURSE   FOREIGN KEY (CNO) REFERENCES COURSE(CNO); 
 ALTER TABLE COURSE  ADD CONSTRAINT FK_COURSE_TEACHER FOREIGN KEY (TNO) REFERENCES TEACHER(TNO);

/*---------------输入记录-------------------*/

mysql-> INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS)  
 VALUES (108 ,‘曾华‘ ,‘男‘ ,‘1977-09-01‘,95033), 
        (105 ,‘匡明‘ ,‘男‘ ,‘1975-10-02‘,95031),  
        (107 ,‘王丽‘ ,‘女‘ ,‘1976-01-23‘,95033), 
        (101 ,‘李军‘ ,‘男‘ ,‘1976-02-20‘,95033),   
        (109 ,‘王芳‘ ,‘女‘ ,‘1975-02-10‘,95031), 
        (103 ,‘陆君‘ ,‘男‘ ,‘1974-06-03‘,95031);

mysql> INSERT INTO TEACHER(TNO,TNAME,TSEX,TBIRTHDAY,PROF,DEPART)  
 VALUES (804,‘李诚‘,‘男‘,‘1958-12-02‘,‘副教授‘,‘计算机系‘), 
        (856,‘张旭‘,‘男‘,‘1969-03-12‘,‘讲师‘,‘电子工程系‘), 
        (825,‘王萍‘,‘女‘,‘1972-05-05‘,‘助教‘,‘计算机系‘),  
        (831,‘刘冰‘,‘女‘,‘1977-08-14‘,‘助教‘,‘电子工程系‘);

mysql> INSERT INTO COURSE(CNO,CNAME,TNO)
       VALUES (‘3-105‘ ,‘计算机导论‘,825), 
              (‘3-245‘ ,‘操作系统‘ ,804),
              (‘6-166‘ ,‘数据电路‘ ,856), 
              (‘9-888‘ ,‘高等数学‘ ,831); 

mysql> INSERT INTO SCORE(SNO,CNO,DEGREE)
        VALUES (103,‘3-245‘,86),(105,‘3-245‘,75),
               (109,‘3-245‘,68),(103,‘3-105‘,92), 
               (105,‘3-105‘,88),(109,‘3-105‘,76),
               (101,‘3-105‘,64),(107,‘3-105‘,91), 
               (108,‘3-105‘,78),(101,‘6-166‘,85), 
               (107,‘6-166‘,79),(108,‘6-166‘,81); 

#1.查询student表中的所有记录的sname,ssex,class列

    -> select sname,ssex,class from student;

#2.查询教师所有的单位即不重复的Depart列
    -> select distinct depart from teacher;

#3.查询Student表的所有记录
    -> select*from student;

#4.查询Score表中成绩在60到80之间的所有记录
1) 
    -> select * from score
    -> where degree>=60 and degree<=80;
2)
    -> select * from score
    -> where degree between 60 and 80;

#5.查询Score表中成绩为85,86或88的记录
#1) 
    -> select * from score
    -> where degree=85 or degree=86 or degree=88;
#2)
    -> select * from score
    -> where degree in(85,86,88);

#6.查询Student表中“95031”班或性别为“女”的同学记录
    -> select * from student
    -> where class="95031" or ssex=‘女‘;

#7.以Class降序查询Student表的所有记录
    -> select * from student
    -> order by class desc;

#8.以Cno升序、Degree降序查询Score表的所有记录
    -> select * from score
    -> order by cno,degree desc;

#9.查询“95031”班的学生人数
    -> select count(*) from student
    -> where class="95031";

#10.查询Score表中的最高分的学生学号和课程号
#1) 
    -> select sno,cno from score
    -> where degree=(select max(degree) from score);
#2)
    -> select sno, cno from score
    -> order by degree desc
    -> limit 1;

#11.查询‘3-105’号课程的平均分
    -> select avg(degree) from score
    -> where cno=‘3-105‘;

#12.查询Score表中至少有5名学生选修的并以3开头的课程的平均分数
    -> select avg(degree) from score
    -> where cno like‘3%‘
    -> group by cno
    -> having count(*)>=5;

#13.查询最低分大于70,最高分小于90的Sno列
mysql> select sno from score
    -> group by sno
    -> having max(degree)<90 and min(degree)>70;

#14.查询所有学生的Sname、Cno和Degree列
#1) 
    -> select sname,cno,degree
    -> from student,score
    -> where student.sno=score.sno;
#2)
    -> select sname,cno,degree
    -> from student inner join score
    -> on student.sno=score.sno;

#15.查询所有学生的Sname、Cname和Degree列
    -> select sname,cname,degree
    -> from student,course,score
    -> where student.sno=score.sno
    -> and course.cno=score.cno;

#16.查询“95033”班所选课程的平均分
    -> select avg(degree)
    -> from score,student
    -> where score.sno=student.sno
    -> and class="95033";

#17.查询选修“3-105”课程的成绩高于“109”号同学成绩的所有同学的记录
    -> select * from score
    -> where cno=‘3-105‘ and degree>(select degree from score
    -> where cno=‘3-105‘ and sno=109);

#19、查询score中选学一门以上课程的同学中分数为非最高分成绩的记录
    -> select*from score
    -> where degree<(select max(degree) from score)
    -> and sno in(select sno from score
    -> group by sno
    -> having count(*)>1);

#20.查询成绩高于学号为“109”、课程号为“3-105”的成绩的所有记录
    -> select*from score
    -> where degree>(select degree from score
    -> where sno=‘109‘
    -> and cno=‘3-105‘);

#21、查询和学号为108的同学同年出生的所有学生的Sno、Sname和Sbirthday列
    -> select sno,sname,sbirthday
    -> from student
    -> where year(sbirthday)=(select year(sbirthday) from student
    -> where sno=108);

#22、查询“张旭“教师任课的学生成绩
    -> select degree
    -> from score,teacher,course
    -> where score.cno=course.cno
    -> and course.tno=teacher.tno
    -> and teacher.tname=‘张旭‘;

#23、查询选修某课程的同学人数多于5人的教师姓名
    -> select tname
    -> from teacher,course,score
    -> where teacher.tno=course.tno
    -> and course.cno=score.cno
    -> group by score.cno
    -> having count(*)>5;

# 24、查询95033班和95031班全体学生的记录
    -> select*from student
    -> where class in(95033,95031);

#25、查询出“计算机系“教师所教课程的成绩表
    -> select degree from score,teacher,course
    -> where score.cno=course.cno
    -> and course.tno=teacher.tno
    -> and teacher.depart=‘计算机系‘;

#26.查询“计算机系”与“电子工程系“不同职称的教师的Tname和Prof
    -> select tname,prof from teacher
    -> where depart=‘计算机系‘
    -> and prof not in(select prof from teacher
    -> where depart=‘电子工程系‘);

#27、查询选修编号为“3-105“课程且成绩至少高于选修编号为“3-245”的同学的Cno、Sno和Degree,并按Degree从高到低次序排序。
mysql> select*from score
    -> where degree>any(select degree from score where cno=‘3-245‘)
    -> and cno=‘3-105‘
    -> order by degree desc;

#28、查询选修编号为“3-105”且成绩高于选修编号为“3-245”课程的同学的Cno、Sno和Degree.
    -> select*from score
    -> where degree>all(select degree from score where cno=‘3-245‘)
    -> and cno=‘3-105‘;

#29、查询所有教师和同学的name、sex和birthday
    -> select sname as name,ssex as sex,sbirthday as birthday
    -> from student
    -> union
    -> select tname as name,tsex as sex,tbirthday as birthday
    -> from teacher;

#30、查询所有“女”教师和“女”同学的name、sex和birthday
    -> select sname as name,ssex as sex,sbirthday as birthday
    -> from student
    -> where ssex=‘女‘
    -> union
    -> select tname as name,tsex as sex,tbirthday as birthday
    -> from teacher
    -> where tsex=‘女‘;

#32、查询成绩比该课程平均成绩低的同学的成绩表
    -> select A.* from score as A
    -> where degree<(select avg(degree) from score as B
    -> where A.cno=B.cno);

#33、查询所有任课教师的Tname和Depart
#1) 
    -> select tname,depart
    -> from teacher,course
    -> where teacher.tno=course.tno;
#2)
    -> select tname,depart from teacher
    -> where tno in (select tno from course);
#3)
    -> select A.tname,A.depart
    -> from teacher A inner join course B
    -> on A.tno=B.tno;
#4)
    -> select tname,depart from teacher as A
    -> where exists(select*from course as B
    -> where A.tno=B.tno);#存在则输出

#34.查询所有未讲课的教师的Tname和Depart
    -> select tname,depart from teacher
    -> where tno  not in(select tno from course);

#35.查询至少有2名男生的班号
#1)
    -> select class from student
    -> group by class,ssex
    -> having count(*)>=2;
#2)
    -> select class from student
    -> where ssex=‘男‘
    -> group by class;

#36、查询Student表中不姓“王”的同学记录
    -> select*from student
    -> where sname not like ‘王%‘;
    -> select sname,year(now())-year(sbirthday) as age
    -> from student;#38、查询Student表中每个学生的姓名和年龄

#37、查询“男”教师及其所上的课程
    -> select teacher.tno,tname,cno
    -> from teacher inner join course
    -> on teacher.tno=course.tno
    -> where tsex=‘男‘;

#38、查询和“李军”同性别并同班的同学Sname
    -> select A.sname
    -> from student as A,student as B
    -> where A.ssex=B.ssex
    -> and A.class=B.class
    -> and B.sname=‘李军‘;

 

MySQL基本语句与经典习题

标签:多表连接   sts   大全   set   教师   any   单位   9.png   求和   

原文地址:https://www.cnblogs.com/liuqing910/p/8652588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!