美文网首页
SQL轻松入门

SQL轻松入门

作者: 李彪_哈工大 | 来源:发表于2017-07-22 02:56 被阅读0次

基础信息

SQL不区分大小写,语句和变量均不区分

  • 什么是SQL?
    SQL stands for Structured Query Language
    SQL lets you access and manipulate databases
    SQL is an ANSI (American National Standards Institute) standard

SQL高频语法

SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

Syntax说明

SELECT

The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.

SELECT 子句
[INTO 子句]
FROM 子句
[WHERE 子句]
[GROUP BY 子句]
[HAVING 子句]
[ORDER BY 子句]

If SELECT all, use SELECT * FROM table_name;

SELECT column1, column2, ...
FROM table_name;

MaxRecursion(number)设置最大的查询递归次数,如果为0,不限次数;未指定,则默认是100;number是0到32767之间的非负整数。

SELECT DISTINCT

The SELECT DISTINCT statement is used to return only distinct (different) values.

SELECT DISTINCT column1, column2, ...
FROM table_name;

WHERE

The WHERE clause is used to extract only those records that fulfill a specified condition.
WHERE 可以在SELECT、UPDATE、DELETE等语句中使用

SELECT column1, column2, ...
FROM table_name
WHERE condition;

运算符Operator

Operator Description
+, -, *, / 加、减、乘、除
% 取余
= Equal
<>、!= Not equal. Note: In some versions of SQL this operator may be written as !=
> Greater than
!> Not greater than
< Less than
!< Not less than
>= Greater than or equal
<= Less than or equal
& 按位与(整型或二进制数据类型)
| 按位或(整型或二进制数据类型)
~ 按位非(整型或二进制数据类型)
^ 按位异或(整型或二进制数据类型)
AND, OR, NOT 逻辑与、或、非
以下逻辑运算符 通常与比较运算符连用
ANY 任意一个true,结果为true
ALL 全部为true,结果为true
BETWEEN ... AND Between an inclusive range
EXISTS 存在则为true
LIKE Search for a pattern,模式匹配则为true
IN '=ANY', To specify multiple possible values for a column

通配符

Operator Description
% 匹配0到多个字符的字符串
_ 匹配单个字符
[] 如[a-z],匹配指定范围或集合内的单个字符
[^] [^a-c], 匹配不在指定范围或集合内的单个字符

ORDER BY

The ORDER BY keyword is used to sort the result-set in ascending or descending order (ASC|DESC).

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

INSERT INTO

The INSERT INTO statement is used to insert new records in a table.
可以加某几列数据进去

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

也可以把一个表格的内容全部添加进去

INSERT INTO table_name
VALUES (value1, value2, value3, ...);

IS NULL \ IS NOT NULL

A field with a NULL value is a field with no value.
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

SELECT column_names
FROM table_name
WHERE column_name IS NULL;
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

UPDATE

The UPDATE statement is used to modify the existing records in a table.

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

DELETE

The DELETE statement is used to delete existing records in a table.

DELETE FROM table_name
WHERE condition;

SELECT TOP number / percent

选择前几个SELECT TOP 50 * FROM Customers;,或前百分之几的数据。SELECT TOP 50 PERCENT * FROM Customers;
不是所有数据库都支持此条语法,MySQL 里用LIMIT:select a limited number of records, 而在Oracle中使用ROWNUM.

SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

MIN() and MAX()

The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.

SELECT MIN(column_name) AS newVal_name
FROM table_name
WHERE condition;

COUNT(), AVG() and SUM()

The COUNT() function returns the number of rows that matches a specified criteria.
The AVG() function returns the average value of a numeric column.
The SUM() function returns the total sum of a numeric column.

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

WITH AS

子查询部分(subquery factoring),用来定义一个SQL片断,该SQL片断会被整个SQL语句所用到。这个语句算是公用表表达式(CTE)。

 with A as (select * from class)
    select *from A  

这个语句的意思就是,先执行select * from class 得到一个结果,将这个结果记录为A ,在执行select *from A 语句。A 表只是一个别名。
可以将重复用到的大批量 的SQL语句,放到with as 中,加一个别名,在后面用到的时候就可以直接用。类似Matlab里的段内function。

1.使用with子句可以让子查询重用相同的with查询块,通过select调用(with子句只能被select查询块引用),一般在with查询用到多次情况下。在引用的select语句之前定义,同级定义with关键字只能使用一次,多个用逗号分割。
2.with子句的返回结果存到用户的临时表空间中,只做一次查询,反复使用,提高效率。
3.在同级select前有多个查询定义的时候,第1个用with,后面的不用with,并且用逗号隔开。
4.最后一个with 子句与下面的查询之间不能有逗号,只通过右括号分割,with 子句的查询必须用括号括起来
5.如果定义了with子句,而在查询中不使用,那么会报ora-32035 错误:未引用在with子句中定义的查询名。(至少一个with查询的name未被引用,解决方法是移除未被引用的with查询),注意:只要后面有引用的就可以,不一定非要在主查询中引用,比如后面的with查询也引用了,也是可以的。
6.前面的with子句定义的查询在后面的with子句中可以使用。但是一个with子句内部不能嵌套with子句。
7.当一个查询块名字和一个表名或其他的对象相同时,解析器从内向外搜索,优先使用子查询块名字。
8.with查询的结果列有别名,引用的时候必须使用别名或*。

AS

as是别名关键字。select 字段 as 别名
在别名的部分,可以使用单引号标明字符串,方括号以避免和系统的关键字冲突。这两种方法都可以在别名内加入空格等特殊字符以改善显示结果。

例:
select
[Anum] as '编   号',
[name]  as [姓         名],
[sex] as [性别],
from [table];

CASE

用于计算条件列表的表达式,并返回可能的结果之一。
sql 的case 类型于编程语言里的 if-esle if-else 或者 switch,但它不用于控制sql程序的执行流程,而是作为列的逻辑使用。

case [input_expression]
when when_expression then result_expression
[...n]
[else else_result_expression]
end
注:其中[]内都是可选的。

简单case函数(case后加表达式,则根据表达式结果返回。)

--简单case函数
select *,
    case sex
    when '1' then '男'
    when '2' then '女’
    else '其他' end groupname
from @table

case搜索函数。(case 后不加表达式,则根据when的条件返回)

--case搜索函数
select *,
    case 
    when sex = '1' then '男'
    when sex = '2' then '女'
    else '其他' end comment
from @table 

这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判定式。
还有一个需要注重的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。

--比如说,下面这段sql,你永远无法得到“第二类”这个结果
case when col_1 in ('a','b') then '第一类'
     when col_1 in ('a') then '第二类'
     else '其他' end  

将sum与case结合使用,可以实现分段统计。
如果现在希望将上表中各种性别的人数进行统计,sql语句如下:

SQL> select
  2    sum(case u.sex when 1 then 1 else 0 end)男性,
  3    sum(case u.sex when 2 then 1 else 0 end)女性,
  4    sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性别为空
  5  from users u;
 
        男性         女性       性别为空
---------- ---------- ----------
         3          2          0

--------------------------------------------------------------------------------
SQL> select
  2    count(case when u.sex=1 then 1 end)男性,
  3    count(case when u.sex=2 then 1 end)女,
  4    count(case when u.sex <>1 and u.sex<>2 then 1 end)性别为空
  5  from users u;
 
        男性          女       性别为空
---------- ---------- ----------
         3          2          0

将case与order by一起使用,可实现复杂排序
如下,存储过程需要支持多种排序,可以传递一个参数变量,然后根据该变量判断操作。

declare @orderby int
set @orderby = 1
 
select * from @stuinfo
order by
    case when @orderby = 1 then id end desc,
    case when @orderby = 2 then id end

注意:这里要用多个case,因为desc需要放在end 后面,否则会有语法错误。

相关文章

网友评论

      本文标题:SQL轻松入门

      本文链接:https://www.haomeiwen.com/subject/bopykxtx.html