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基本语句与经典习题的更多相关文章

  1. MySQL 常用语句 (汇集)

    原文地址:MySql常用语句作者:wuyanle 一.mysql常用语句 创建,删除和最基本查询: 显示数据库  mysql->show databases; 创建数据库  mysql-> ...

  2. mysql sql语句大全(转载)

      1.说明:创建数据库 CREATE DATABASE database-name 2.说明:删除数据库 drop database dbname 3.说明:备份sql server --- 创建 ...

  3. MySQL的语句执行顺序

    MySQL的语句执行顺序 MySQL的语句一共分为11步,如下图所标注的那样,最先执行的总是FROM操作,最后执行的是LIMIT操作.其中每一个操作都会产生一张虚拟的表,这个虚拟的表作为一个处理的输入 ...

  4. strace追踪mysql执行语句

    一.strace参数 strace是Linux环境下的一款程序调试工具,用来监察一个应用程序所使用的系统调用及它所接收的系统信息.追踪程序运行时的整个生命周期,输出每一个系统调用的名字,参数,返回值和 ...

  5. MySQL 基础语句

    MySQL 基础语句 多个知识点 ----------------------------------------------------------------------------------- ...

  6. MySQL DELETE语句和TRUNCATE TABLE语句的区别

    MySQL DELETE语句和TRUNCATE TABLE语句的区别 2010-10-08 16:05 佚名 互联网 字号:T | T 在MySQL数据库中,DELETE语句和TRUNCATE TAB ...

  7. 使用 xlrd 模块实现对excel 的读取、excel转json 、excel 转 mysql insert 语句

    #-*- coding:utf-8 -*- # 处理 excel 中的 area 为 Mysql insert 语句 import xlrd, json, codecs, os # data = xl ...

  8. MySQL update语句和insert插入语句写法完全不一样啊,不要搞混

    1.mysql update 语句: update user set name = 'xiaoming',age = 18 where uid = 3000; 更新记录时update操作也不需要写ta ...

  9. T-SQL:SQL Server-SQL语句大全经典

    ylbtech-SQL Server-Doc-Help:SQL Server-SQL语句大全经典 SQL Server 流程控制中的 While 语句. 1,SQL语句大全经典返回顶部 .说明:创建数 ...

随机推荐

  1. 安装coreseek cannot find input file: src/Makefile.in 错误解决方法

    安装coreseek 出现了cannot find input file: src/Makefile.in 解决方法如下 >autoheader >automake --add-missi ...

  2. 修改windows7中文件的权限

    1.修改ntkrnlpa.exe的权限 2.鼠标右键,选择"属性" 3.单击"安全"选项,选择"高级" 4.在高级安全设置中,选择" ...

  3. Servlet配置

    1.在Servlet中,Servlet的配置 @WebServlet(name="csvExportServlet",urlPatterns="/servlet/CsvE ...

  4. 用SPSS 画 人口金字塔(限SPSS 13.0以上)

    现在网络上人口金字塔较多的是用excel来实现(可参考链接),但是用spss的步骤又很不明确,于是乎,想着自己试试. 在 SPSS 软件中,绘制人口金字塔是 SPSS13.0 新增的一种图形, 因此只 ...

  5. WebService之CXF注解报错(二)

    WebService之CXF注解 1.具体报错如下 五月 04, 2014 11:24:12 下午 org.apache.cxf.wsdl.service.factory.ReflectionServ ...

  6. EJB相关的面试题

    1.EJB是基于哪些技术实现的?并说出SessionBean和EntityBean的区别,StatefulBean和StatelessBean的区别. (1)EJB包括Session Bean.Ent ...

  7. javaWeb之自动发送邮件生日祝福(ServletContextListener监听)

    在看完本随笔仍然不理解的可以看  javaWeb邮箱发送  :里面有具体的邮箱服务器配置 企业在员工生日当天发送邮箱生日祝福: 一般是用监听器完成:  而合适的监听是ServletContextLis ...

  8. 芝麻HTTP:在阿里云上测试Gerapy教程

    1.配置环境 阿里云的版本是2.7.5,所以用pyenv新安装了一个3.6.4的环境,安装后使用pyenv global 3.6.4即可使用3.6.4的环境,我个人比较喜欢这样,切换自如,互不影响. ...

  9. 从零一起学Spring Boot之LayIM项目长成记(六)单聊群聊的实现

    文章传送门: https://my.oschina.net/panzi1/blog/1577007 并没有放弃博客园,只是 t-io 在 oschina发展.用了人家的框架,也得帮人家做做宣传是吧~~

  10. php 数组排序得方法

    $sort1 = array_column($list_bloc[1], 'value');//按照$list_bloc[1]里面的value做降序排序 array_multisort($sort1, ...