第一天sql总结

建表相关操作

CREATE TABLE table_name( 
   column1 datatype, 
   column2 datatype, 
   column3 datatype, 
   ..... 
   columnN datatype, 
   PRIMARY KEY( one or more columns ));

创表时添加约束


主键约束
CREATE TABLE student(
	sno char(10) NOT NULL PRIMARY KEY,
	sname varchar(8) NULL,
	ssex char(2) NULL,
	sbirthday date NULL,
	sdept char(16) NULL,
	saddress varchar(50) NULL,
	speciality varchar(20) NULL,
	
)
设置联合主键
 CREATE TABLE tb_emp5
    -> (
    -> name VARCHAR(25),
    -> deptId INT(11),
    -> salary FLOAT,
    -> PRIMARY KEY(name,deptId)
    -> );
检查约束
create table teacher(
	tno char(3) primary key not null,
	tname varchar(8) null,
	tsex char(2) null check(tsex='男' or tsex='女'),
	tbirthday date null,
	tdept char(16) null
)	
create table teaching(
	cno char(5) not null,
	tno char(3) not null,
	cterm tinyint null check(cterm > 1 or cterm < 10) 
)

建表后添加约束

检查约束
alter table student
add constraint CK_gender check(ssex='男' or ssex='女')

插入数据

指定每一列
insert into course(cno,Cname)
	values('C01',	'数据库'),
			('C02',	'数学'),
			('C03',	'信息系统'),
			('C04',	'操作系统')
			
不指定列
insert into course
	values('C01',	'数据库'),
			('C02',	'数学'),
			('C03',	'信息系统'),
			('C04',	'操作系统')

查询相关操作

SELECT column-list  
FROM table_name  
[WHERE condition]  
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

排序

-- 查询选修了c01课程的学生的学号及其成绩,查询结果按分数降序排列
select sno,degree from sc
where cno = 'c01'
-- desc 降序
-- asc 升序
ORDER BY degree DESC

去重

select distinct sno from sc

Like模糊查询
百分号(%)
下划线(_)

/*百分号表示零个,一个或多个字符。 下划线表示单个数字或字符。 */

-- 查询所有姓“刘”的学生信息。
select * from student
where sname LIKE '刘%'
-- 查询生源地不是山东省的学生信息
select * from student
where  saddress not like '山东%'

分组查询

select cno, count(sno) as '数量' from sc
-- as是指定别名
group by cno

where 同 having 的区别

-- 1.执行顺序
-- where>聚合函数(sum,min,max,avg,count)>having
-- 2.充当作用
-- where在分组之前过滤数据(应为其在分组前执行)
-- having在分组之后过滤数据,且条件中经常包含聚组函数,

-- 查询被两名以上学生选修的课程的课程号
select cno from sc group by cno
having count(cno) >=2

select sum(score) from student  where sex='man' group by name having sum(score)>210

IN 与 = 的区别
相同点:均在WHERE中使用作为筛选条件之一、均是等于的含义
不同点:IN可以规定多个值,等于规定一个值

-- 两个等价表达
select * from Websites where name in ('Google','教程');
select * from Websites where name='Google' or name='教程';
posted @ 2022-10-18 11:25  main(void)  阅读(22)  评论(0编辑  收藏  举报
.c_ad_block { display: none !important; } #ad_t2{ display: none !important; }