SQL初级第二课

随着我们数据库越来越复杂 我们要掌握的姿势也要也来越多....

首先建立个表

create table shop
(
code int primary key identity (1,1),
name varchar(50) not null,
price int not null,
brand varchar(50) not null,
BB int not null,
[from] varchar (50) not null
)
insert into shop values('冰红茶',3,'康师傅','12','福建');
insert into shop values('冰红茶',4,'娃哈哈','12','北京');
insert into shop values('冰绿茶',3,'康师傅','12','福建');
insert into shop values('冰绿茶',3,'统一','24','山东');
insert into shop values('方便面',2,'康师傅','24','江苏');
insert into shop values('方便面',3,'福满多','12','上海');
insert into shop values('方便面',2,'康师傅','24','福建');

drop table shop
--注:SQL不像VS一样,SQL要选中内容才可以让计算机接收

下面信息,分割线划分的是不同的内容,所以对于内表有冲突,执行完一个分割线内的内容请执行

--drop table shop,然后选中表重新执行,再去完成查询。


--我们建立了一个商品的数据库shop,BB=best before,from=产地,因为from牵扯到系统关键词我们用[]区分。
-------------------------------------我是华丽的分割线--------------------------------------------
--我们要查看shop表的前3个:
select top 3 * from shop;
--查看前两个方便面信息:
select top 2 * from shop where name='方便面';
-------------------------------------我是华丽的分割线--------------------------------------------
--这里有好多价钱是重复的,我们想看分别都是有多少钱的货
select distinct price from shop;
--查看保质期都有多久的
select distinct bb from shop;
-------------------------------------我是华丽的分割线----------------------------------------------
--有些时候我们需要把数据排列,请用 order by 或 order by desc
--请按价格由低到高排列
select * from shop order by price asc;   --asc是默认的 可以不写.
--如果价格想由高到低排列
select * from shop order by price desc   ---desc不可以省略.
--但是我们发现虽然按照顺序排列了,但是价格相同的有好多,辣么我们想让3块钱的商品按照保质期长短排列
select *from shop order by price,BB; --这里面也是有顺序的,先排列 price然后再BB,BB按照升序在不影
响price的情况下排列。
-------------------------------------我是华丽的分割线--------------------------------------------
--分组 group by;分组在以后的时候会用的,目前先知道有这么个东西,目前的作用同distinct.
--例如用age分组
select price from shop group by price;
--这里要讲的就是我们用了什么组了,前面和后面必须一致,语意,在shop表里分组price然后显示price,如果
我们说select price from shop group by BB,那么我们分组了BB然后查询price,毫无意义。
-------------------------------------我是华丽的分割线--------------------------------------------
----运算符   
 --算数运算符: + - * / %
 --比较运算符: > < >= <= !=  <> !< !>
 --逻辑运算符: || &&
 --修饰符:     all any some in not
--这里讲一下 in, in 表示在什么范围之内
--查询价格是 2和4的商品
select * from shop where price in (2,4); --这里相当于 price=2 or price=4;
--子查询
--查询康师傅品牌不是福满多品牌价钱的东东;
select * from shop where price not in(select price from shop where brand='福满多');
--理解,这句话有些绕,意思是我们要查询出福满多商品的价格,然后在比对康师傅商品的东西,如果康师傅
--的商品与福满多商品一致那么不输出,其余的输出。 首先我们先得出福满多商品的价格
--(select price from shop where brand='福满多')括号里实际上是另外的计算,结果就是3。这样的好处是
--如果商品成千上万我们不可能一一输入,所以计算机需要代码来代替我们输入,这是一个很省力的方法,关
--键是思想。
--------------------------主人吃饭去了留下一条华丽的分割线----------------------------------------

原文地址:https://www.cnblogs.com/18553325o9o/p/4441538.html