目录
零、码仙励志
一、建库和建表
二、内连接的用法(inner join)
1.select ...... from A,B 的用法
2.select ...... from A,B where ......的用法(sql92标准)
3.select ...... from A join B on ......的用法(sql99标准)
不被嘲笑的梦想是没有价值的。愿你的梦想不只是空谈的情怀,而是实干的姿态
create database scort
use scort
create table emp
(
empno int primary key,
ename nvarchar(10),
sal int,
deptno int
)
insert into emp values (7369,'smith',3000,20);
insert into emp values (7499,'allen',1500,10);
insert into emp values (7521,'ward',2850,30);
insert into emp values (7566,'jones',2000,30);
insert into emp values (7654,'martin',5000,10);
insert into emp values (7698,'blake',1800,30);
create table dept
(
deptno int primary key,
dname nvarchar(10),
loc nvarchar(10)
)
insert into dept values (10,'accounting','new york');
insert into dept values (20,'research','dallas');
insert into dept values (30,'sales','chicago');
insert into dept values (40,'operations','boston');
create table salgrade
(
grade int primary key,
lostl int,
hisal int
)
insert into salgrade values (1,700,1200);
insert into salgrade values (2,1201,1400);
insert into salgrade values (3,1401,2000);
insert into salgrade values (4,2001,3000);
insert into salgrade values (5,3001,6000);
解释:将两个表或两个以上的表以一定的连接条件连接起来,从中检索出满足条件的数据。
注意:inner join 可以简写为 join
1.产生的结果:行数是A和B的乘积,列数是A和B之和。或者说把A表的每一条记录和B表的每一条记录组合在一起,形成的是个笛卡尔积。
2.select ...... from A,B和select ...... from B,A的输出查询结果本质上是一样的,只是看起来A,B表的前后顺序不一样而已。
3.实例演示:
select * from emp,dept
select * from dept,emp
1.select ...... from A,B where ......和select ...... fromB,A where ......查询结果本质上一样
select * from emp,dept where sal>2000
2.如果俩个表或多个表有相同列名的时候,where后面必须加表名。
select * from emp,dept where deptno=10 --error
select * from emp,dept where emp.deptno=10
select * from emp,dept where dept.deptno=10
3.三张表连接在一起
--把工资大于2000的ename,dname和grade输出
select "E".ename,"D".dname,"S".grade
from emp "E",dept "D",salgrade "S"
where "E".deptno="D".deptno and
("E".sal>"S".lostl and "E".sal<"S".hisal) and
"E".sal>2000
1.select ...... from A join B on ......和select ...... from B join A on ......查询结果本质上一样
2.俩张表连接在一起
select * from emp
join dept
on 1=1
select * from emp
join dept
on emp.deptno=dept.deptno
3.三张表连接在一起
--把工资大于2000的ename,dname和grade输出
select "E".ename,"D".dname,"S".grade
from emp "E"
join dept "D"
on "E".deptno="D".deptno
join salgrade "S"
on "E".sal>"S".lostl and "E".sal<"S".hisal
where "E".sal>2000
本篇博客来自于郝斌老师视频教程的总结以及笔记的整理,仅供学习交流,切勿用于商业用途,如有侵权,请联系博主删除,博主QQ:194760901