Create a database and data tables grouped data CRUD sql query sub-query basis grammar review

Reference links:

A. Create a database syntax

--用master数据库
use master
--判断数据库是否存在,若存在则删除
if exists (select * from sysdatabases where name='数据库名称')
drop database 数据库名称
--创建数据库
create database 数据库名称
on(                 --指定主文件的属性
    name='',        --文件的逻辑名称(数据之间的相互关系)
    filename='',    --文件的物理名称(数据存储的路径)
    size='',        --文件的初始大小
    maxsize='',     --文件的最大值
    filegrowth=''   --文件的增长方式
)
log on(             --指定日志文件的属性
    name='',        --文件的逻辑名称
    filename='',    --文件的物理名称
    size='',        --文件的初始大小
    filegrowth=''   --文件的增长方式
)
--查看数据库
exec sp_helpdb 数据库名称;
--修改数据库名称
alter database 数据库名称
modify name='';
--修改数据库文件
alter database 数据库名称
modify file(        
    name='',
    filename='',
    size='',
    filegrowth=''
)

II. Create a data table

--指定用什么数据库
use 数据库名称
--判断数据表是否存在,若存在则删除
if exists (select * from sysobjects where name='数据表名称')
drop table 数据表名称
--创建数据表
create table 数据表名称(
    --一般不直接添加约束
    字段名称 字段类型 字段特征(默认值DF_、标识列、主键PK_、关系FK_、索引UQ_、检查CK_、非空)       
)

--为字段添加约束
alter table 数据表名称
add constraint 约束名称 约束(指定字段) [references 主表(主键或唯一键)];
--删除约束
alter table 数据表名称
drop constraint 约束名称;

--增加外键约束时,设置级联删除、级联更新  on delete cascade;
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]  删除
[ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]  更新
--on--在做何种操作的时候做相应的处理
--NO ACTION--不做任何操作:该报错就报错,可以删除就删除
--CASCADE:级联:删除主表,对应的从表数据也会删除,更新也一样
--SET NULL:如果删除主表的记录,那么对应的从表记录的字段值会被设置为null,前提是从表的这个字段的值可以是null
--SET DEFAULT :删除主表记录,从表的记录的对应字段值设置为默认值,前提是你之前为这个字段设置了默认值

--修改字段的类型及约束
alter table 数据表名称
alter column 字段名称 字段类型 约束;
--添加字段
alter table 数据表名称
add 字段名称 字段类型 [not null];   
--删除某个字段
alter table 数据表名称
drop column 字段名称;
--修改字段名称
exec sp_rename '数据表名称.原字段名称','新字段名称','column';

III. Adding data

--一次添加一行数据,实参与形参 参数类型 参数个数 参数顺序 都必须一致
insert into 表名(形参)      
values(实参)

--1.默认约束可以不指定列名
--2.自增不能显示的添加
--3.允许为null值的字段可直接设置null值,也可不指定列名

--一次添加多行数据时添加顺序不是按照书写的顺序添加的,而是按照第一个字段的首a-z字母或者数字从小到大添加的
--一次添加多行数据
insert into 表名(形参)
select 实参 union
select 实参;
--或者
insert into 表名(形参)
values(实参),(实参);

--从别的表中copy数据
insert into 表1(形参)  
select 实参 from 表2;

--将从数据源选择的数据插入到新表中并显示,新表是系统创建的,之前必须不存在
select * into 新表 from 数据源;
--将从数据源选择后得到的结果集添加到目的表中, 目的表必须存在
insert into 目的表 select * from 数据源;

IV. Deleting Data

--标识列不会从标识种子开始,可以回滚(恢复数据)
delete from 表名;
--条件与查询语句中条件一样:关系、逻辑运算符、like、in、between...
delete from 表名 where 条件;
--标识列会从标识种子开始
truncate table 表名;

V. modify data

--条件与查询语句中条件一样:关系运算符、逻辑运算符、like、in、between...
update 表名 set 字段=值,... where 条件

1. operators and built-in functions

Relational operators: = < > >= <= != <>
logical operators:not / and / or / is null / is not null

Built-in functions:

  • String Functions:
    • CharIndex('ab','cdab') Back "3" - returns "ab" in position "CDAB" will return to the first position of a letter
    • Len('我是谁')Back "3" - returns a string length
      - substring('abd',2,2)returns "BD" - from the second position to intercept a string of length 2
  • Date function:
    • GetDate() Returns the current date
    • DateName(DW,'2009-09-09') Return specify a date as a string of part of the "Wednesday"
    • DateDiff(dd,'2009-09-09','2010-10-09')Returns the interval between two dates, yy is the year, mm is the month, dd is the day
      - DatePart(DW,'2009-09-09')return to "4" to return to a specified date as an integer part of (the United States: Sunday is the first day of December for the first month)
  • Mathematical Functions:
    • Abs(-1) Absolute value
    • Ceiling(24.1)The smallest integer greater than 24.1
      - Floor(24.1)largest integer less than 24.1
    • round(18.6) A positive or negative rounding, the result is the value of a certain length
  • System functions
    • Convert(varchar(3),123) Back "123" converting data types
    • DataLength("12中国") Back "6" returns the number of bytes of any data type, 2-byte characters

VI. Query data

1. Basic grammar

select top|distinct 值/[percent] */表名.字段 别名,... ['上海' as 城市],...   from 表名 别名   where 条件   group by 字段    having 条件   order by 字段别名
  1. top 值/[percent]: Generally used in conjunction with the order by; when the result set is to take a percentage of the decimal ceiling; limit line is the last step to do a query, sort, limit line
  2. distinct 字段: Filter out duplicate records
  3. 表名.字段: Internal inquiries more quickly this way; if you select a group by field: meet record in value is one relationship
  4. 字段 as 别名; 字段 别名; 别名=字段; - three ways can
  5. You can add constants are listed :'上海' as 城市
  6. where conditions:
    • 关系(> < >= <= != <>)
    • Logical operators (and / or / not)
    • 字段 [not] in(具体值1、具体值2)/(子查询): Use in particular represents a range of values, in agreement requirements specified range of data types; subqueries can be used
    • 字段 [not] between 数值1/日期1 and 数值2/日期2: If it is determined numeric or date range may be used between ... and
    • 字段 [not] like '张%'、'张_'、'1[1-8]'、'[^21-35]' --'1[1-8]'表示11-18: [^21-35]Representation in addition to the 1,2,3,5 (wildcard valid only in fuzzy query)
      • % : Represents any number of any characters
      • ** _ **: stands for any single character
      • [] : Represents any of a range of values of a specific character [0-9][a-z]matches only a character
      • [^] : Representative is not within the specified range, on the [] which have this sense - negated value only MSSQL Server support, with not like other MSDB
  7. group by : The data group specified column, the column with the same value of the row designated as a group
  8. having条件: Field either packet, either the polymerization conditions: the condition where the same
    • where clause and having clause difference:
      • where clause relating to a single row, having clauses related to the group
      • where clause can not be polymerized directly as a function of the search condition, and having a function may be polymerized as a search condition, but having not use field aliases
      • where clause with different execution order having clauses
  9. order by 字段 [desc]...: The default is asc, you can sort to multiple fields

2. Polymerization function

Aggregate function is a set of data fields after some set of screening results were analyzed.

--聚合函数:参数一般是字段
select max(字段),min(字段)...  /  select count(*),max(字段) from 表名 where 条件
  • max(数值、字符串、日期) : Selecting the maximum value of the specified data range: can be any type of polymerization, if it is non-numeric values ​​on the alphabetical sorted
  • min(数值、字符串、日期) : Minimization of the specified data range: can be any type of polymerization, if it is non-numeric values ​​on the alphabetical sorted
  • avg(数值) : Averaging the specified range of data values ​​which can only be polymerized, the polymerization can not date
  • sum(数值) : Request and the specified data range, it can only numerical polymerization, the polymerization can not date
  • count(*/一个字段) : Seeking the number of records satisfying the condition, there is no relationship with the field; computing the number of records or a specified number of non-null value of the column
    • The default is minimal space character
    • String: Character AZ; phonetic spelling characters; the higher the value the more alphabetical
    • Date: The date the sooner the smaller the value

3. grouping queries

Query 7 Keywords:

select [top] from [where] [group by] [having] [order by]

Query order of the statements:

5.select 7.top 字段列表 1.from  表列表 2.where 源数据筛选条件 3.group by 分组统计字段列表 4.having 对分组统计结果集做筛选 6.order by 得到最终结果集之后的数据重排

1. First acquired from the data source 2 and then filtering where data source 3 again to group by group data sources, 4. and then having to do packet filtering statistics of the result set, [Polymerization Polymerization function of the result set analysis] 5 again to set the result select the filtered display, 6. order by data then the final result set rearrangement, 7 finally again the result set top limit lines and then

Troubleshooting:

  • Why where you can not use aggregate functions (aggregate function can not be directly used as search criteria where clause)? - need to filter out the data source and then using the result set aggregation function then analyzes show polymerization
  • Why not use the student having the columns in the table? - grouped result set only for the result field after the grouping, it will ignore the student table in other fields
  • Why are not we having to use an alias? - First packet statistics result sets do the screening, during the show
  • Why can order by using an alias? - the final result set to be displayed, the data rearrangement
  • When the group is not a group, you may be used having screening, but there is no practical significance
  • And did not count on the display classid, while filtering the data source is a packet count value, and a plurality classid values ​​for each field value in the result set must be filtered to-one relationship. Individual field values ​​can not be applied group, having clause must be a column set of columns
  • Group general question is appearing in the query 'every' or 'individual' ... when the word grouping

4. join query (connection table)

Table connection:

  1. Cross-connect (Cartesian product): from 结果集 cross join 结果集
  2. The connector (conditional relationship sufficient matches): from 结果集 inner join 结果集 on 条件--on conditions (with the major outer field key relationship)
  3. An outer connector (recovery not match): from 结果集 left|right|full join 结果集 on 条件

Syntax Note: Many online are written, following such an approach is not recommended

--国际组织ANSI-SQL 89版语法(当时还没有外连接)
select * from Employee, Title;      --交叉连接
select * from Employee t1, Title t2 where t1.titleId=t2.titleId;    --内连接

Attention to the problem:

  1. Join query is a plurality of tables corresponding conditions by splicing into a result table

    • Select * from table can be connected; show all fields of all the
    • Select from table may be connected to the field; if the same name selection field, it must be specified in the table; not the same name field may not specify
  2. After the connection must be taken from the table alias list, or to produce an intermediate table, the table with the same name is generated because of an error

  3. En query can be implemented to achieve where - the fifth point of the description

  4. Alternatively where clause having clauses: can be replaced when performing the same function: HAVING where used may be replaced with a set of columns during screening, not replaced with a screening function where use of the polymerized

    • where StuNo = 6 ; Filtering the source data StuNo row 6 (equivalent to StuNo for the group 6) - This query faster, after all, less than the following statement
    • group by StuNo having StuNo = 6; StuNo the packet, followed by screening of group 6 StuNo
    1. from 结果集1 ... join 结果集2 ... join ... on 连接条件--on can not be used where the replacement, syntax error will occur

    from 结果集1,结果集2,... where 连接条件 --where can not be used on replacement

5.union operator and type conversion functions

Operators 1.union

union operator: union may incorporate a plurality of result sets

Use two premises and a note:

  • The combined number of columns in the result set must match exactly
  • Column corresponding to the type of merging a plurality of result sets needs to be consistent (interchangeable)
  • The results are set only the first name of a result set about (note)

union and the union all the difference:

  • union: do distinct operations, record filtering repeat
  • union all: the operation is not distinct, it is higher combined efficiency, because there is no need to judge whether the result of repeated recording
2. Type Conversion Functions
  • cast (as the target source data type): print '我的总成绩是:'+cast(200 as varchar(30))
  • convert (target type, source data, format):
    • print '我的总成绩是:'+convert(char(3),200)
    • select convert(char(30),GETDATE(),121)

6. subquery

Subquery: In a query, the results of a query as a condition for another query, then the query is called sub-query, the query conditions is called the outer query.

Query and multi-valued scalar sub-query:

  • Scalar subquery: single value subquery (query result is a single value) = WHERE field (single value subquery)
  • Multi-valued subquery: multi-valued subquery (a query result is more than one value) where field in (multi-value subqueries)

Independent sub-queries and the relevant sub-query:

  • Independent sub-query: Field and the outer query does not matter, you can check out the results of an independent

  • Correlated subquery: conditions in a field with an external lookup table fields are linked, not independent inquiry results

    子查询中 where 字段 = 外表名.字段(多值时也可以)

Guess you like

Origin www.cnblogs.com/itzlg/p/12503804.html