The SQL study notes

Insert data into the database:

The first form does not specify the name of the column you want to insert data only provide value to be inserted, you can add a new row of data:

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

Second, if you want to add value for all columns in the table, you do not need to specify column names in the SQL query. However, make sure the same order as the columns of the table values.

INSERT INTO语法如下所示: INSERT INTO table_name VALUES (value1, value2, value3, ...);

You can check out by another table in the SELECT statement field values, then this data to populate the table, that table Field another query to the table, the data to be inserted is one to one.

INSERT INTO first_table_name [(column1, column2, ... columnN)] 
SELECT column1, column2, ...columnN FROM second_table_name [WHERE condition]; 

SQL INSERT INTO SELECT syntax we can replicate all the columns from one table to another table already exist in:

INSERT INTO table2 SELECT * FROM table1;

Or we may want to copy an existing row to another table:

INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;

When you create a table, NULL basic syntax is as follows:

SQL> CREATE TABLE CUSTOMERS( ID INT NOT NULL,
 NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, 
ADDRESS CHAR (25) , 
SALARY DECIMAL (18, 2), 
PRIMARY KEY (ID) )

Here, NOT NULL means that for a given column, you must explicitly assigned in accordance with its data type. There are two and not used to define NOT NULL, that is to say these columns can be NULL. Value is NULL fields are left blank in the process of recording created fields.

top / limit / rownum Example The following SQL statement to select the first three records from the "Customers" table: 

SELECT TOP 3 * FROM Customers;

The following SQL statement shows an example of the use of equivalent LIMIT clause: 

SELECT * FROM Customers LIMIT 3;

The following SQL statement shows an example of the use of ROWNUM equivalent of: 

SELECT * FROM Customers WHERE ROWNUM <= 3;

 

The SQL IN operator IN operator allows you to specify multiple values ​​in the WHERE clause. IN OR operator is shorthand for a plurality of conditions.

SQL IN 语法 SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);

或者 SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT STATEMENT);

DROP INDEX statement

DROP INDEX statement to drop the table index.

DROP INDEX syntax for the MS Access: DROP INDEX index_name ON table_name

DROP INDEX Syntax for MS SQL Server is: DROP INDEX table_name.index_name

DROP INDEX syntax for DB2 / Oracle is: DROP INDEX index_name

DROP INDEX syntax for MySQL: ALTER TABLE table_name DROP INDEX index_name

DROP TABLE statement

DROP TABLE statement to drop the table.

DROP TABLE table_name DROP DATABASE 语句

DROP DATABASE statement to delete database.

DROP DATABASE database_name TRUNCATE TABLE 语句

 

If we only need to remove the data in the table, without deleting the table itself, then how do we do?

Use TRUNCATE TABLE statement: TRUNCATE TABLE table_name

 

SQL ALTER TABLE Syntax To add a column to the table, use the following syntax:

ALTER TABLE table_name ADD column_name datatype  

To delete a column in a table, use the following syntax (Note that some database systems do not allow this to delete a database table columns):

ALTER TABLE table_name DROP COLUMN column_name  

To change the data type of the columns in the table, use the following syntax:

SQL Server / MS Access: ALTER TABLE table_name ALTER COLUMN column_name datatype

My SQL / Oracle: ALTER TABLE table_name MODIFY COLUMN column_name datatype

The syntax for MySQL

The following SQL statement "Persons" table in the "ID" column is defined to automatically increment (auto-increment) primary key field:

CREATE TABLE Persons 
( ID int NOT NULL AUTO_INCREMENT,
 LastName varchar(255) NOT NULL, 
 FirstName varchar(255), 
 Address varchar(255),
 City varchar(255), 
 PRIMARY KEY (ID) )

MySQL use AUTO_INREMENT keyword to perform an auto-increment (auto-increment) task.

By default, AUTO_INREMENT starting value is 1, each new record by one.

NOT NULL constraint: to ensure that data in a column can not have a NULL value DEFAULT constraint: provide default values ​​UNIQUE constraint when the column unspecified data used: to ensure that all data in the column varies primary key constraint: uniquely identifies a data table row / recording foreign key constraint: uniquely identify a row in the other tables / records CHECK constraints: all values ​​satisfy a certain condition to ensure this constraint index column: for fast creation or retrieval of data in the database

There are several different SQL connections:

SQL JOIN clause is used to combine two or more rows from tables together based on a common field between the tables

It is to first determine a primary table as a result set, then, the rows to other tables selectively "Connection" on the main table in the result set.

The connector (INNER JOIN): when there is a match both tables, rows before returning. (Select two rows of tables are returned)

Left connecting (LEFT JOIN): returns all rows in the left table, even if there is no match in the right table row. Right connection (RIGHT JOIN): return all rows in the right table, even if there is no matching left table row.

Fully connected (FULL JOIN): as long as one table there is a match, return line.

Cartesian connector (CARTESIAN JOIN): Returns the Cartesian product of two or more records in the table set.

JOIN order execution

The following is the general structure JOIN query:

SELECT <row_list> 
FROM <left_table> <inner|left|right> 
JOIN <right_table> ON <join condition> 
WHERE <where_condition>

Its implementation in the following order (SQL statements to be executed in the first one is always the FROM clause):

FROM: around two tables on the implementation of Cartesian product, resulting in the first table vt1. The number of rows n * m

(N is the number of rows in the left table, m is a number of rows in the right table)

ON: The ON condition progressive screening vt1, vt2 inserts the result in

JOIN: add an external line.

If LEFT JOIN (LEFT OUTER JOIN) is specified, the first to traverse over each row of the left table,

Wherein vt2 line will not be inserted into vt2, the remaining fields will be filled row is NULL, the VT3 is formed;

If the specified RIGHT JOIN is the same reason.

If you specify a INNER JOIN, the external line is not added, the insertion process is ignored,

vt2 = vt3 (INNER JOIN filters thus placed in the ON or WHERE is no difference between the results of execution)

WHERE: row pair filtering conditions for vt3, satisfying the condition is outputted to vt4

SELECT: Remove the specified field to vt4 vt5

PS: In fact, we can see LEFT JOIN and RIGHT JOIN no different from the semantics,

The results depend on the difference between the two left and right placement order table

SQL INTERSECT clause: to combine two SELECT statements, but only returns the results of two SELECT statements in both rows.

Dynamic SQL:

1. <where> </ where> add dynamic conditions where

<If test = ""> </ if> dynamic determination, determines whether the argument passed correctly

select * from emp 
<where> 
    <if test="name != null and name !=''"> 
        name like concat('%',#{name},'%') 
    </if> 
    <if test="job != null and job != ''"> 
        and job = #{job} 
    </if> 
</where>

2.<foreach collection="ids" item="id" separator="," open="(" close=")"></froeach>

<insert id="addBatchSave"> 
    insert into tbl_employee(last_name,email,gender) 
    values 
    <foreach collection="emps" item="emppp" separator=","> 
        (#{emppp.lastName},#{emppp.email},#{emppp.gender}) 
    </foreach> 
</insert>

3. <set> </ set> Dynamic Updates

<update id="updateEmp"> 
    update emp 
    <set> 
        <if test="name != null and name != ''"> 
            name=#{name}, 
        </if> 
        <if test="job != null and job != ''"> 
            job=#{job} 
        </if>
    </set> 
    where id=#{id} 
</update>

4. <sql id = "idName"> </ sql> frequently used fragment encapsulation sql, reference is <includ refid = "idName">

<sql id="insertColumn"> 
    <if test="_databaseId=='mysql'"> 
        id,last_name,email,gender 
    </if> 
    <if test="_databaseId=='oracle'"> 
        id,last_name,email,department_id 
    </if> 
</sql> 
<insert id="addEmployeeBysql" databaseId="mysql"> 
    insert into tbl_employee( <!-- 引用外部定义的sql --> 
    <include refid="insertColumn" ></include> ) 
        values (#{id},#{lastName},#{email},#{gender}) 
</insert>

5.<trim prefix="where" prefixOverrides="" suffix="" suffixOverrides="and">

prefix = "": Prefix: trim tab body importance to fight the result of the entire string string. prifix entire string to fight a prefix string

prifixOverrides = "": override prefix: removing the entire string of characters in front of the extra

suffix = "": Suffix: to fight the entire string plus a suffix string

suffixOverrides = "": suffix cover: removing the entire string of characters followed by excess

Alternatively integral values ​​beginning with the prefix, by replacing part of the overall final suffix.

select * from emp 
    <trim prefix="where" prefixOverrides="" suffix="" suffixOverrides="and"> 
        <if test="job != null and job != ''"> 
            job=#{job} and 
        </if> 
        <if test="topid != null and topid != ''"> 
            topid=#{topid} and 
        </if> 
    </trim>

6.<chose><when test=""></when><when test=""></when></chose>

When first when established, it will not execute down. As long as a front does not hold, it is down to judge, find the end of the establishment.

select * from emp 
<where> 
    <choose> 
        <when test="name != null and name != ''"> 
            name like concat('%',#{name},'%') 
        </when> 
        <when test="job != null and job !=''"> 
            and job=#{job} 
        </when> 
    </choose> 
</where>

join on the back of the condition and the condition where the difference between:

1、select * from tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name='AAA' 2、select * from tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=‘AAA’) 第一条SQL的过程: 1、中间表on条件:tab1.size = tab2.size

 

tab1.id

tab1.size

tab2.size

tab2.name

1

10

10

AAA

2

20

20

BBB

2

20

20

CCC

3

30

(null)

(null)

2, and then filtering the intermediate table where conditions: tab2.name = 'AAA'

 

tab1.id

tab1.size

tab2.size

tab2.name

1

10

10

AAA

Second SQL procedure: 1, the intermediate table on condition: tab1.size = tab2.size and tab2.name = 'AAA'

 

tab1.id

tab1.size

tab2.size

tab2.name

1

10

10

AAA

2

20

(null)

(null)

3

30

(null)

(null)

sql in date, the difference date_format, str_to_date of:

1、date(datestring)

datestring date expression is legitimate

如:SELECT date('2017-02-09 15:25:46.635') FROM dual; -->'2017-02-09'

2、date_format(datestring,format)

datestring argument is legitimate date. format output format predetermined date / time.

如:SELECT STR_TO_DATE('2017-02-09 15:25:46.635','%Y-%m-%d')

FROM dual; -->'2017-02-09'

3.str_to_date(str,format)

Using the function str_to_date (str, format), wherein, format as shown in the above format still.

Notably, the format and the format required str consistent format, e.g. str_to_date ( '2017-08-07 16:56:12', '% Y-% m-% d% H:% i:% s' ), an error occurs if inconsistent. No longer.

 

SQL optimization: common optimization rules

Table 2.1 connections

  • The more connections tables, the poorer the performance
  • If possible, split into a plurality of connecting procedure executed one
  • Preferentially executed can significantly reduce the amount of data connection, not only reduces the complexity, it is possible to easily perform as expected
  • If the inevitable multi-table joins, it is likely to be a design flaw
  • External link poor results, because it must be around the table to table scan
  • Try to use inner join query

2.2 use a temporary table

If unavoidable, consider using temporary tables or table variables to store intermediate results.

2.3 less subqueries

2.4 Nested view

Not too deep, the general view of the nested preferably not more than 2.

3, SQL write Precautions

3.1 NULL column

Null columns use the index does not make sense any column that contains null values ​​will not be included in the index. Therefore, where the statement is null or is not null statement optimizer is not allowed to use the index.

3.2 concat or ||

or concat string concatenation operator || mysql and oracle, if the function of the column operation, it also ignores the meeting using the index. Compare the following query:

-- 忽律索引 select ... from .. where first_name || '' || last_name = 'bill gates' ;

-- 使用索引 select ... from .. where first_name = 'bill' and last_name = 'bill gates' ;

3.3 like

The wildcard in the first place, can not use the index, otherwise you can.

- Unable to use the index select .. from .. where name like '% t%';

- You can use the index select .. from .. where name like 't%';

3.4 order by

Do not use the order by clause of non-indexed columns or nested expressions, this will result in reduced performance.

3.5 Not operation

not use the index calculation can not be changed to other operations can use the index. as follows:

- Invalid Index select .. from .. where sal = 3000;!

- Index commencement select .. from .. where sal <3000 or sal> 3000;

3.6 where与having

select .. from .. on .. where .. group by .. having .. order by .. limit .., upper sql statement syntax structure, wherein on, where a filter and having a behavior, the behavior of the filter can be completed in advance, the more you can reduce the amount of data to be passed to the next stage, so if the filtering behavior in having to complete in where, you should prioritize where to achieve.

3.7 exists in alternative

It is not in the least effective, due to the sub-query table full table scan. Consider using external links or not exists. as follows:

- correct SELECT * FROM EMP

WHERE EMPNO > 0 AND EXISTS (SELECT ‘X' FROM DEPT

WHERE DEPT.DEPTNO = EMP.DEPTNO AND LOC = ‘MELB')

- Error SELECT * FROM EMP

WHERE EMPNO > 0 AND DEPTNO IN(SELECT DEPTNO FROM DEPT WHERE LOC = ‘MELB')

3.8 Index

The benefits of binary search index can be achieved, the time complexity is O (log2n)

But there are costs, the need for additional space to store the index data, and each insert, update and delete on the index will be updated, so the increase will be more than 4,5 times the disk IO. So give some of the unnecessary use of the index field increased the index will reduce system performance. For oracle speaking, SQL statements, try to uppercase, lowercase internal need to write to the National Cheng Kung University, and then executed.

Do not use the function in the index column, it will stop using the index, a full table scan, as follows:

-- 错误 SELECT … FROM DEPT WHERE SAL * 12 > 25000;

- correct SELECT ... FROM DEPT WHERE SAL> 25000/12;

3.9> and> =

- 4 positioned directly to the recording (recommended) select .. from .. where SAL> = 4;

- 3 to first locate, find again after a (not recommended) select .. from .. where SAL> 3;

3.10 union instead of or

Columns in the index, or may alternatively operate using union. or action on the indexed column caused a full table scan.

-- 高效: SELECT LOC_ID , LOC_DESC , REGION FROM LOCATION

WHERE LOC_ID = 10 UNION SELECT LOC_ID , LOC_DESC , REGION FROM LOCATION

WHERE REGION = 'MELBOURNE'

-- 低效: SELECT LOC_ID ,LOC_DESC ,REGION FROM LOCATION

WHERE LOC_ID=10 OR REGION ='MELBOURNE'

3.11 is null & is not null

If the column can be empty, avoiding the use of the index. For index plurality of columns, at least, ensure that at least one column is not blank. For multi-column index, only access the first column of the index will be enabled, if access to the back of the column using a full table scan.

- inefficient: (Failure Index) SELECT .. FROM DEPARTMENT WHERE DEPT_CODE IS NOT NULL;

- Efficient: (effective index) SELECT .. FROM DEPARTMENT WHERE DEPT_CODE> = 0;

3.12 union & union all

union having deduplication operation, the calculation time increases. no need to re-union all, but will include the same record. Under the same function, the preferred union all operation.

Database view: A view is derived from one or several base table (view) table, it is different from the basic table is a virtual table;

CREATE VIEW Student(Sno,Sname,Ssex,Sage,Sdept) AS SELECT SX.Sno,SX.Sname,SY.Ssex,SX.Sage,SY.Sdept FROM SX,SY WHERE SX.Sno=SY.Sno;

 

Published 15 original articles · won praise 0 · Views 273

Guess you like

Origin blog.csdn.net/weixin_45146962/article/details/105113375