SQL Sever 学习笔记二——查询基础;算术、比较、逻辑运算符
发布日期:2021-05-07 08:52:02 浏览次数:19 分类:技术文章

本文共 2559 字,大约阅读时间需要 8 分钟。

查询

1、查询SQL Sever中已建立好的数据库

select * from sysdatabases;

2、查看当前使用的数据库中所有表信息

use shop--当前使用的数据库select * from sysobjects where type='U'select * from sysobjects where type not in('U','S','SQ','IT','D')  --当前使用的数据库中所有表约束exec sp_help Product  --查看指定表结构

3、查看表中所有数据

select * from Product;

4、查询指定的列

select product_id,product_name,purchase_pricefrom Product;

5、为列设定别名

select product_id as id,product_name as name,purchase_price as pricefrom Product;--4.别名也可以使用中文,中文需要用双引号括起来select product_id as "商品编号",product_name as "商品名称",purchase_price as "进货单价"from Product;

6、常数的查询

--5.常数的查询select '商品' as string,38 as number,'2009-02-24' as date,product_id,product_namefrom Product;

7、从结果中删除重复行

--6从结果中删除重复行,使用select中的子句distinctselect distinct product_type from Product;--在使用distinct时,null也被视为一类数据,被保留下来select distinct purchase_price from Product;/*在多列之前使用distinctdistinct关键字只能用在第一个列名之前*/select distinct product_type, purchase_price from Product;

8、根据WHERE语句来选择记录

\quad \quad 前面的例子都是将表中存储的数据全都选取出来,但实际上并不是每次都需要选取出全部数据,大部分情况都是要选取出满足“商品种类为衣

服”“销售单价在 1000 日元以上”等某些条件的数据

--7根据where子句指定查询的条件,提取出想要的内容select product_name,product_type from Productwhere product_type='衣服';--也可以不选取出作为查询条件的列select product_name from Productwhere product_type='衣服';

\quad \quad SELECT 语句通过 WHERE 子句来指定查询数据的条件。在 WHERE子句中可以指定“某一列的值和这个字符串相等”或者“某一列的值大于这个数字”等条件。执行含有这些条件的 SELECT 语句,就可以查询出只符合该条件的记录了。

9、算术运算符

--8 算术运算符:+、-、*、/。所有含有null的计算,结果均是nullselect product_name,sale_price,sale_price *2 as "sale_price_x2"from Product;

10、比较运算符

在这里插入图片描述

--9比较运算符--9.1符号=select product_name,product_typefrom Productwhere sale_price=500;--9.2符号不等于<>select product_name,product_typefrom Productwhere sale_price<>500;--9.3大于等于>=select product_name,product_type,sale_pricefrom Productwhere sale_price>=1000;/*字符串类型的数据原则上按照字典顺序进行排序,不能与数字的大小顺序进行混淆。不能对null使用比较运算符*/

不能对NULL使用比较运算符

--10用来判断是否为null的is null运算符--10.1选取为null的记录select product_name,purchase_price from Product where purchase_price is null;--10.2 选取不为null的记录select product_name,purchase_price from Product where purchase_price is not null;

11、逻辑运算符

--11.1 NOT运算符否定select product_name,product_type,sale_pricefrom Product where not sale_price>=1000;--多个查询条件结合--11.2 AND运算符,交select product_name,purchase_price from Productwhere product_type='厨房用具' and sale_price>=3000;--11.3 or运算符,并select product_name,purchase_pricefrom Productwhere product_type='厨房用具' or sale_price>=3000;/*AND运算符优先于OR运算符可以通过括号改变两者的优先级*/select  product_name,product_type,regist_date from Productwhere product_type='办公用品'and (regist_date='2009-09-11' or regist_date='2009-09-20');

AND运算符的优先级高于OR运算符。想要优先执行OR运算符时可以使用括号。

上一篇:SQL Sever 学习笔记三——聚合查询
下一篇:SQL Sever学习笔记一——SQL

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月20日 04时33分34秒