【SQL】SQL数据库基础语句学习(一)

版权声明:转载请声名出处,谢谢 https://blog.csdn.net/u010591976/article/details/82052893
--2018/09/06
--对表table进行操作
--创建:create   --修改: alert    --删除:drop   --增加:add
--create table 表名(数据段1,数据段2,……)
--alert table 表名
--drop table表名 删除数据结构
--add 

--对表中的数据进行操作
--增加 insert into 表名(字段1,字段2,……) values(value1,value2,……)、
--修改(更新) update
--删除 delete
--查找 select


--增加一条数据
--insert into book1(编号,书名,定价) values(3,'白与黑',38.9)

----------------查询语句 select [] from 表名称----------------------------
--查询所有数据
select * from book1 

--查询排序 select [] from 表名称 order by 一个字段 [asc/desc]
--根据顺序查询数据(asc升序,desc降序)
select * from book1 order by 编号 desc

--按照编号升序,查询前5条数据
select top 5 * from book1 order by 编号 asc

--按照编号查询后几条数据
select top 5 * from book1 order by 编号 desc

--查询特定几条数据(子查询)
select * from book1 where 编号 in (6,7,8)
-- in (某列字段,不是表数据,在最里面的select语句写的是select 编号,而不是select *)
select top 3 * from book1 where 编号 in 
(
 select top 5 编号 from book1 order by 编号 desc
) order by 编号 asc

--查询定价最高的,排序
select top 1 * from book1 where 书名='悲惨世界' order by 定价 desc

select * from book1 where 书名='悲惨世界' and 出版社='上海出版社'

--查询计数
select COUNT(*) as 行数 from book1 
select COUNT(编号) as 编号个数 from book1 
--分组查询计数
select 出版社,COUNT(*) from book1 where 书名='悲惨世界' group by 出版社 


--查询书名,select 字段 (as) 新的字段名称(别名)
select 书名 as 书大名 from book1
select 书名  书大名 from book1
--起别名
select 编号,书名 as 书大名,定价 as 价格 from book1

--多表联合查询
select * from book1 
select * from author1

--左连接
select * from book1 a
left join author1 b on a.作者ID=b.id
where b.name='张三'

select a.编号,a.书名,a.出版社,a.定价,b.name  as 作者 from book1 a
left join author1 b on a.作者ID=b.id
where b.name='张三'

--左连接,右连接的区别
select * from book1 a
left join author1 b on a.作者ID=b.id
where b.name='张三'

--全连接
select * from book1 a
inner join author1 b on a.作者ID=b.id
where b.name='张三'


----------------------------------------更新数据 
--uppdate 表名称 set [] where []
update TestDB.dbo.book1 set 书名='小王子4' where 编号='2'

温故知新:
排序
- select [] from 表名称 order by 字段

多表查询
select * from book1
select * from author1

连接:左连接&右连接
左连接和右链接的区别?
左连接只影响右表,右链接只影响左表。

  • 左连接 (left join)

    select * from table1 left join tbale2 on table1.id=table2.id
    这条sql语句返回结果 table1表中的数据全部返回 table2表中的数据只返回满足where条件的

  • 右链接 (right join)

    select * from table1 right join table2 on table1.id=table2.id
    这条sql语句返回结果 table2表中的数据全部返回 table1表中的数据只返回满足where条件的

  • 全连接 (inner join)

    select * from table1 inner join table2 on table1.id = table2.id
    这条sql语句返回结果 显示满足条件的数据 并不以谁为主表

猜你喜欢

转载自blog.csdn.net/u010591976/article/details/82052893