SQL data integrity and the multi-table queries and sub-queries

Data integrity

1. What is data integrity

Ensure the preservation of user-entered data into the database is correct.

 

2. How to add data integrity

Add a constraint to the table when you create a table

 

3. Integrity Category

Entity integrity, domain integrity, referential integrity

 

Entity integrity

1. What is the entity integrity

Table row (record) on behalf of an entity (Entity)

 

2. The role of entity integrity

Identify each row of data is not repeated. Row-level constraints

 

3. constraint type

Primary key constraint (primary key)

The only constraint (unique)

Automatic growth column (auto_increment)

 

 

The primary key constraint

Features: each table have a primary key. The only data, and not be null

Adding way

CREATE TABLE table name (field data type 1 primary key, the field data type 2);

CREATE TABLE table name (data type of the field 1, field 2 data type, primary key (primary key fields to be set));

CREATE TABLE table name (data type of the field 1, field 2 data type, primary key (primary key of the primary key 2));

 

Primary key

Two fields with the same data at the same time, only the primary key constraint violation.

 

1. create table

2. go to modify the table, add a primary key

ALTER TABLE student ADD CONSTRAINT PRIMARY KEY (id);

 

The only constraint

Features: data specified column can not be repeated, can be null

format

CREATE TABLE table name (1 Field Name Field Data Type Data Type UNIQUE 2);

 

Automatic growth column

Features: automatic data specified column growth, even if the data is deleted, or continue down the serial number removed

format

CREATE TABLE table name (1 Field Name Data Type PRIMARY KEY AUTO_INCREMENT, the data type field UNIQUE 2);

 

 

Domain integrity

use

Limit this cell data is correct, the comparison of other cells in the column as such does not

Domain represents the current cell

 

Domain integrity constraints

Data type: numeric type, date type, string type

 

Non-empty constraint (not null)

CREATE TABLE table name (1 Field Name Data Type PRIMARY KEY AUTO_INCREMENT, the second data type field UNIQUE not null);

 

The default value constraints (default)

CREATE TABLE table name (1 Field Name Data Type PRIMARY KEY AUTO_INCREMENT, the second data type field UNIQUE not null default 'M');

When inserted, the value of which is directly to the default values

 

 

Referential integrity

1. What is referential integrity

It refers to a correspondence between the table and the table

Normally provided by the primary bond between the two tables, the foreign key relationship, two or write trigger table to achieve.

There are two tables correspond to reference the integrity of their data in the process of insert, update, delete, the system will be modified to correspond to the table and another table were compared, thereby preventing operation of some incorrect data.

2. Note

Primary keys and foreign keys in the database must be consistent with the type;

If the two tables have to type InnoDB

After setting the referential integrity, the contents of which the foreign key, the contents have to be among the primary key

 

Field as the primary key of a table is provided which, provided the primary key table based

CREATE TABLE student(sid int PRIMARY key,name varchar(50) not null,sex varchar(10) default '男');

 

When you create a table, foreign key, foreign key of the child table

CREATE TABLE score( sid INT, score DOUBLE, CONSTRAINT fk_stu_score_sid FOREIGN KEY(sid) REFERENCES student(sid) );

 

Relationships between tables

One: monogamy

Many relationship: A person can have many cars, all requests for access to a vehicle owned by individuals.

-- Person表 CREATE TABLE person( id int primary key NOT NULL, name VARCHAR(50), age int, sex CHAR(1) );

 

-- Car表 CREATE TABLE car( cid int primary key, cname varchar(50), color varchar(25), pid int, CONSTRAINT fk_Person FOREIGN KEY(pid) REFERENCES person(id) );

 

Many relationship:

Student enrollment, a student may have many courses, each course for more students to choose.

A student can have multiple teacher, and a teacher can have more than one student

1. Create table teacher

CREATE TABLE teacher( tid INT PRIMARY KEY auto_increment, name VARCHAR(50), age int, gender char(1) DEFAULT '男' );

2. Create a table of students

CREATE TABLE student( sid int PRIMARY KEY auto_increment, name VARCHAR(50) NOT NULL, age int, gender CHAR(1) DEFAULT '男' );

3. Create a table of students and teachers

CREATE TABLE tea_stu_rel( tid INT, sid INT );

4. Add Foreign Key

ALTER TABLE tea_stu_rel ADD CONSTRAINT fk_tid FOREIGN KEY(tid) PEFERENCES teacher(tid); ALTER TABLE tea_stu_rel ADD CONSTRAINT fk_sid FOREIGN KEY(sid) PEFERENCES student(id);

 

Why split the table? Avoid large numbers of redundant data

 

 

Multi-table query

The combined result set

1. What is the combined result set

The combined result set is to query the results of two select statements merged together

 

2. merge two ways the result set

Merging repeated removal recording UNION

UNION ALL is not removed when the combined duplicate records

format:

SELECT * FROM 表1 UNION SELECT * FROM 表2;

SELECT * FROM 表1 UNION ALL SELECT * FROM 表2;

Examples

1. Create a table

CREATE TABLE A(name varchar(10),score int); CREATE TABLE B(name varchar(10),score int); INSERT INTO A VALUES('a',10),('b',20),('c',30); INSERT INTO B VALUES('a',10),('b',20).('d',40);

2.UNIONSELECT * FROM A UNION SELECT * FROM B;  

 

 

 

3.UNION ALLSELECT * FROM A UNION ALL SELECT * FROM B;

 

 

 

Precautions

The combined results of the two: the number of columns, the column must be the same type.

 

Join query

1. What is the connection query

Queries can also be called across the table, you need to associate multiple tables query

 

2. What is the Cartesian set

Hypothesis set A = {a, b}, set B = {0,1,2},

Cartesian product of the two sets of {(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}.

It can be extended to a plurality of sets of

Meanwhile queries two tables, there is the Cartesian set of results

 

Since the alias to the table when the query

SELECT * FROM student stu,score sc;

 

3. multi-table joint investigation, how to ensure data is correct

When the query should the primary and foreign keys consistent SELECT * FROM stu st, score sc WHERE st.id = sc.sid; 

 

 

 Primary table data among the reference data among the sub-table

principle

Progressive judgment, leaving an equal, not equal whole do not

 

 

 Classified according to the connection

En

First, the equivalent connection

id number (value) of only two simultaneous display table

SELECT * FROM stu st INNER JOIN score sc ON st.id = sc.sid;

Table check constraints associated with multiple primary foreign key is the same, but changing the wording.

Write-back of only the main foreign key ON

If there are conditions where write directly behind

SELECT st.name,sc.score,sc.km FROM stu st INNER JOIN score sc ON st.id = sc.sid WHERE score>=70;

Multi-table joint investigation and there are conditions to write and direct

 

Second, multi-table joins

The establishment of student scores, chart

 

 

 

99 using the joining method

SELECT st.name,c.name,sc.score FROM stu st,score sc,course c WHERE st.id = sc.sid AND sc.cid = c.cid;

Use inline query

SELECT st.name,c.name,sc.name FROM stu st INNER JOIN score sc ON st.id = sc.sid INNER JOIN course c ON sc.cid = c.cid;

 

Third, non-equivalent connection

Example Table

 

 

Query the names of all employees, wages, the name of the department and the level of wages

1. Query the names of all employees, wages

SELECT ename,salary FROM emp;

 

 

 

 

2. Query the names of all employees, wages and all sectors - SELECT e.ename, e.salary, d.dname FROM emp e, dept d WHERE e.deptno = d.deptno; SELECT e.name, e.salaru, d.dname FROM emp e JOIN dept d ON e.deptno = d.deptno;

 

 

 

3. Query the names of all employees, wages and wage levels and where the department

SELECT e.ename,e.salary,d.dname,g.grade FROM emp e JOIN dept d ON e.deptno = d.deptno JOIN salgrade g ON e.salary BETWEEN g.lowSalary AND g.highSalary;

 

Fourth, external connection

1. The left outer connector (left connector)

Meet the conditions of the same two data tables check out, if there is not the same among the left of the data table, the data table on the left is also among the check out.

Among all the data table on the left found the right watch them, just find out the condition of contents

 

 

When using the connector, seven weeks does not check out, no score, the absent. All the test over the test scores of students to check out.

SELECT st.name,sc.score,sc.km FROM stu st,score sc WHERE st.id = sc.sid

 SELECT st.name,sc.score,sc.km FROM stu st INNER JOIN score sc ON st.id = sc.sid;

 

 

 

Use the left join query for all students and student test scores

SELECT st.name,sc.score,sc.km FROM stu st LEFT OUTER JOIN score sc ON st.id = sc.sid;

 

 

 

All data is left connected to the left table will among identified, of which only found the right table to meet the conditions of data

You can not write omitted outer

Query, two tables may not be required to establish the primary foreign key constraint

 

2. The right outer connector (right connection)

All data among the right connection will find out the right, the left table only find out which satisfy the conditions of data

SELECT st.name,sc.score,sc.km FROM stu st RIGHT JOIN score sc ON st.id = sc.sid;

 

All in all the right data tables found among the left table only find out the condition of the recording

Standing on the perspective to see the table, use the left left put the connection table of contents among all found the right found to meet the criteria.

Using the right connection, put the data table on the right among all find out. The left found to meet the conditions.

 

Fifth, the natural connection

Join query produces unwanted Cartesian set, we usually use the primary foreign key relationship equation to remove it.

The natural connection without you having to give the primary foreign key equation, it will automatically find this equation

That do not have to write condition

 

Claim

Two table names and column connection type of column as the identical conditions

Removes the same column

SELECT * FROM stu NATURAL JOIN score;

 

 

Subqueries

1. What is a subquery

A select statement contains another complete select statement.

Or two or more SELECT, then that is a sub-query.

 

2. The position of the sub-queries appear

After the where, the select query results as a condition of the value of another select

After the from, to check out the new results as a table;

 

Example Table

 

 

use

Xiang Yu query with the same department staff person

1. First, find out where the department number Xiang Yu

SELECT deptno FROM emp WHERE ename = '项羽';

 

2. According to again check the number of employees in the same department

SELECT ename,depatno FROM emp WHERE depatno = (SELECT deptno FROM emp WHERE ename = '项羽');

Article 1 the result of check out when the condition statement Day 2

 

Queries wages higher than Yaojin employees

1. identify Yaojin wages

SELECT salary FROM emp WHERE ename = 'Yaojin';

2. go check out the name of the employee record is greater than the value of the results ISOLATED

SELECT ename,salary FROM emp WHERE salary > (SELECT salary FROM emp WHERE ename='程咬金');

 

Paid more than 30 department employee information for all

1. First, find out the 30th highest paid man department

SELECT MAX(salary) FROM emp WHERE deptno = 30;

2. then query the entire table is greater than 30, the highest wage sectors of the man

SELECT ename,salary FROM emp WHERE salary > (SELECT MAX(salary) FROM emp WHERE deptno = 30);

 

Queries jobs and wages and Daji same employee information

1. Da has been working to identify and wages

SELECT job,salary FROM emp WHERE ename='妲己';

The query results as a condition to go to work and the same wages

SELECT ename,job,salary FROM emp WHERE (job,salary) IN (SELECT job,salary FROM emp WHERE enname='妲己');

Since the two conditions, the determination using the IN

 

There are more than two employee information direct reports

1. group all the superior numbers

SELECT mgr,GROUP_CONCAT(mgr) FROM emp GROUP BY mgr;

2. Identify greater than 2 and greater than 2 illustrates two subordinates

SELECT mgr,GROUP_CONCAT(mgr) FROM emp GROUP BY mgr HAVING COUNT(*) >= 2;

3. When the row of the query results as employee number on the bar

SELECT ename FROM emp WHERE empno IN (SELECT mgr FROM emp GROUP BY mgr HAVING COUNT(*) >= 2)

 

Queries employee number for employees to name 7788, staff salaries, department name, department address

SELECT e.name,e.salary,d.dname,d.local FROM emp e,dept d WHERE e.deptno = d.deptno AND empno = 7788;

 

Since the connection

7369 seeking employee number, name, number, and manager Managers Name

SELECT * FROM emp WHERE empno = (SELECT mgr FROM emp WHERE empno=7369);

Above this method can only check out the name of a manager

Since the connection: connect your own, surnamed

SELECT * FROM emp e1,emp e2 WHERE e1.mgr = e2.empno AND e1.empno = 7369;

 

Old nine school community members produced

Guess you like

Origin www.cnblogs.com/ljxt/p/11608843.html