


Detailed explanation of constraints, multi-table queries and subqueries in MySQL
1. Primary key constraints of constraints
Constraints: Constraints are added to columns to constrain columns.
1. Primary key constraint (unique identification): non-null, unique, referenced
When a column of the table is designated as the primary key, the class cannot be empty or have duplicate values. There are two ways to specify the primary key when creating a table:
CREATE TABLE stu( sid CHAR(6) PRIMARY KEY, sname VARCHAR(20), age INT, sex VARCHEAR(10) ); CREATE TABLE stu( sid CHAR(6) , sname VARCHAR(20), age INT, sex VARCHEAR(10), PRIMARY KEY(sid) );
Specify the sid column as the primary key column, that is, add a primary key constraint to the sid column.
Specify the primary key when modifying the table:
ALTER TABLE stu ADD PRIMARY KEY(sid);
Delete primary key:
ALTER TABLE stu DROP PRIMARY KEY;
2. Primary key auto-increment
Because the characteristics of the primary key column are: it must be unique and cannot be empty, so we usually specify the primary key as an integer type, and then set its automatic growth to ensure the unique and non-null characteristics of the primary key column when inserting data.
Specify the primary key auto-increment when creating a table
CREATE TABLE stu( sid INT PRIMARY KEY AUTO_INCREMENT, sname VARCHAR(20), age INT, sex VARCHEAR(10) );
Set the primary key auto-increment when modifying the table:
ALTER TABLE stu CHANGE sid sid INT AUTO_INCREMENT;
Delete the primary key auto-increment when modifying the table:
ALTER TABLE stu CHANGE sid sid INT ;
Test the primary key auto-increment:
INSERT INTO stu VALUES(NULL,'zhangsan',23,'man'); INSERT INTO stu(sname,age,sex) VALUES(NULL,'zhangsan',23,'man');
3. Non-null constraints
Because some columns cannot be set to null values, you can add non-null constraints.
For example:
CREATE TABLE stu ( sid INT PRIMARY KEY AUTO_INCREMENT, sname VARCHAR(20) NOT NULL, age INT, sex VARCHAR(10) );
A non-null constraint is set on the sname column.
4. Unique constraints
Some columns in the garage cannot have repeated values, so you can add unique constraints to the columns.
For example:
CREATE TABLE stu ( sid INT PRIMARY KEY AUTO_INCREMENT, sname VARCHAR(20) NOT NULL UNIQUE, age INT, sex VARCHAR(10) );
2. Concept model
1. Object model: in Java it is domain, for example: User, Student.
2. Relational model: tables in the database, 1-to-many, 1-to-1, many-to-many.
3. Foreign key constraints
The foreign key must be the value of the primary key of another table (the foreign key must reference the primary key.)
Foreign keys can be repeated
Foreign keys can be empty
1. Add foreign key constraints when creating
CREATE TABLE dept ( deptno INT PRIMARY KEY AUTO_INCREMENT, dname VARCHAR(50) ); insert into dept values(10,'研发部'); insert into dept values(20,'人力部'); insert into dept values(30,'财务部'); CREATE TABLE emp ( empno INT PRIMARY KEY AUTO_INCREMENT, ename VARCHAR(50), deptno INT, CONSTRAINT fk_emp_dept FOREIGN KEY(dno) REFERENCES dept(deptno) ); CREATE TABLE dept ( deptno INT PRIMARY KEY AUTO_INCREMENT, dname VARCHAR(50) ); INSERT INTO dept VALUES(10,'研发部'); INSERT INTO dept VALUES(20,'人力部'); INSERT INTO dept VALUES(30,'财务部'); INSERT INTO emp(empno,ename) VALUES(null,'zhangsan'); INSERT INTO emp(empno,ename,deptno) VALUES(null,'lisi',10); INSERT INTO emp(empno,ename,deptno) VALUES(null,'zhangsan',80); /* Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`mydb2`.`emp`, CONSTRAINT `fk_emp_dept` FOREIGN KEY (`deptno`) REFERENCES `dept` (`deptno`)) */
2. Add foreign key constraints when modifying the table:
ALTER TABLE emp ADD CONSTRAINT fk_emp_dept FOREIGN KEY(dno) REFERNCES dept(deptno);
4. Database relational model
1. One-to-one relationship
It is special to establish a one-to-one relationship in a table. It is necessary to make the primary key of one of the tables both a primary key and a foreign key.
CREATE TABLE hasband ( hid INT PRIMARY KEY AUTO_INCREMENT, hname VARCHAR(50) ); CREATE TABLE wife ( wid INT PRIMARY KEY AUTO_INCREMENT, wname VARCHAR(50), CONSTRAINT fk_wife_hasband FOREIGN KEY (wid) REFERENCES hasband(hid) );
2. Many-to-many relationship
To establish a many-to-many relationship in a table, you need to use an intermediate table, that is, you need three tables, and use two foreign keys in the intermediate table to reference them respectively. The primary keys of the other two tables.
CREATE TABLE student ( sid INT PRIMARY KEY , ...... ); CREATE TABLE teacher( tid INT PRIMARY KEY , ...... ); CREATE TABLE stu_tea ( sid INT, tid INT, ADD CONSTRAINT fk_stu_tea_sid FOREIGN KEY (sid) REFERENCES student(sid) , ADD CONSTRAINT fk_stu_tea_tid FOREIGN KEY (tid) REFERENCES teacher(tid) );
Establish a relationship in the intermediate table, such as:
INSERT INTO stu_tea VALUES(5,1); INSERT INTO stu_tea VALUES(2,2); INSERT INTO stu_tea VALUES(3,2);
5. Multi-table query
1, Classification
Merge result set
Connection query
Subquery
2. Merge result query
Requires that the type and number of result set columns in the merged table are the same
UNION, remove duplicate rows
UNION ALL, do not remove duplicate rows
SELECT * FROM 表1名 UNION ALL SELECT * FROM 表2名;
3. Connection query
①Category
Inner join
Outer join
Left outer join
Right outer join
Full outer join (mysql does not support it)
Natural join (a simplified method)
②Inner join
Dialect: SELECT * FROM table 1 alias 1, table 2 alias 2 WHERE alias 1.xx=alias 2.xx;
SELECT * FROM emp,dept WHERE emp.deptno=dept.deptno; SELECT e.ename, e.sal, d.dname FROM emp e, dept d WHERE e.deptno=d.deptno;
Filter by conditions Remove useless information from Cartesian product.
Standard: SELECT * FROM table 1 alias 1 INNER JOIN table 2 alias 2 ON alias 1.xx=alias 2.xx;
SELECT e.ename, e.sal , d.dname FROM emp e INNER JOIN dept d ON e.deptno=d.deptno;
Natural: SELECT * FROM table 1 alias 1 NATURAL JOIN Table 2 Alias 2;
SELECT e.ename, e.sal , d.dname FROM emp e NATURAL JOIN dept d;
All records queried by the inner join meet the conditions
③Outer join
Left outer: SELECT * FROM Table 1 Alias 1 LEFT OUTER JOIN Table 2 Alias 2 ON Alias 1.xx = Alias 2.xx;
The records in the left table will be queried regardless of whether they meet the conditions, while the records in the right table can be retrieved only if they meet the conditions. Records in the left table that do not meet the conditions will be null in the right table.
SELECT e.ename, e.sal , IFNULL(d.dname,'无部门') AS dname FROM emp e LEFT OUTER JOIN dept d ON e.deptno=d.deptno;
Left outer natural: SELECT * FROM table 1 Alias 1 NATURAL LEFT OUTER JOIN Table 2 Alias 2 ON Alias 1.xx=alias 2.xx;
Right outer: SELECT * FROM table 1 Alias 1 RIGHT OUTER JOIN Table 2 Alias 2 ON Alias 1.xx = Alias 2.xx;
The records in the right table will be queried regardless of whether they meet the conditions, while the records in the left table can be retrieved only if they meet the conditions. Records in the right table that do not meet the conditions will be null in the left table.
Right outer natural: SELECT * FROM Table 1 Alias 1 NATURAL RIGHT OUTER JOIN Table 2 Alias 2 ON Alias 1.xx = Alias 2.xx;
Full link: You can use UNION to complete Fully connected.
SELECT e.ename, e.sal , d.dname FROM emp e LEFT OUTER JOIN dept d ON e.deptno=d.deptno UNION SELECT e.ename, e.sal , d.dname FROM emp e RIGHT OUTER JOIN dept d ON e.deptno=d.deptno;
4. Subquery
There is a query in the query (check the number of select keywords)
①The position where it appears
is used as a condition after WHERE Exists as a table after
FROM (multiple rows and multiple columns)
②Condition
Single row and single column: SELECT * FROM table 1 alias 1 WHERE column 1 [=, > ,=,
SELECT * FROM emp WHERE sal=(SELECT MAX(sal) FROM emp);
Multiple rows and single column: SELECT * FROM table 1 alias 1 WHERE column 1 [IN ,ALL,ANY] (SELECT column FROM table 2 alias 2 WHERE condition);
SELECT * FROM emp WHERE sal > ANY (SELECT sal FROM emp WHERE job='经理') ;
Single row and multiple columns: SELECT * FROM table 1 alias 1 WHERE (column 1, column 2) IN (SELECT column 1, column 2 FROM table 2 alias 2 WHERE condition);
SELECT * FROM emp WHERE (job,deptno) IN (SELECT job,deptno from emp WHERE deptno=30) ;
Multiple rows and multiple columns: SELECT * FROM table 1 alias 1, (SELECT...) Table 2 alias 2 WHERE condition;
The above is the detailed content of Detailed explanation of constraints, multi-table queries and subqueries in MySQL. For more information, please follow other related articles on the PHP Chinese website!

The steps to create and manage user accounts in MySQL are as follows: 1. Create a user: Use CREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password'; 2. Assign permissions: Use GRANTSELECT, INSERT, UPDATEONmydatabase.TO'newuser'@'localhost'; 3. Fix permission error: Use REVOKEALLPRIVILEGESONmydatabase.FROM'newuser'@'localhost'; then reassign permissions; 4. Optimization permissions: Use SHOWGRA

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

The disadvantages of MySQL compared to other relational databases include: 1. Performance issues: You may encounter bottlenecks when processing large-scale data, and PostgreSQL performs better in complex queries and big data processing. 2. Scalability: The horizontal scaling ability is not as good as Google Spanner and Amazon Aurora. 3. Functional limitations: Not as good as PostgreSQL and Oracle in advanced functions, some functions require more custom code and maintenance.

MySQL supports four JOIN types: INNERJOIN, LEFTJOIN, RIGHTJOIN and FULLOUTERJOIN. 1.INNERJOIN is used to match rows in two tables and return results that meet the criteria. 2.LEFTJOIN returns all rows in the left table, even if the right table does not match. 3. RIGHTJOIN is opposite to LEFTJOIN and returns all rows in the right table. 4.FULLOUTERJOIN returns all rows in the two tables that meet or do not meet the conditions.

MySQL's performance under high load has its advantages and disadvantages compared with other RDBMSs. 1) MySQL performs well under high loads through the InnoDB engine and optimization strategies such as indexing, query cache and partition tables. 2) PostgreSQL provides efficient concurrent read and write through the MVCC mechanism, while Oracle and Microsoft SQLServer improve performance through their respective optimization strategies. With reasonable configuration and optimization, MySQL can perform well in high load environments.

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor