Home Database Mysql Tutorial MySQL database multi-table operation

MySQL database multi-table operation

Jun 11, 2018 pm 11:15 PM
mysql

1. Foreign key

1. What is a foreign key: A foreign key refers to one or more columns in another table. The referenced columns should have primary key constraints or Uniqueness constraints. Foreign keys are used to establish and strengthen the connection between data in two tables.


# The gid in the Student table is the class ID of the student, which is the primary key ID in the grade table. Then gid can be used as a foreign key to the table student. The referenced table, that is, table grade, is the master table; the table that refers to the foreign key, that is, table student, is the slave table, and the two tables are in a master-slave relationship. Table student can use gid to connect the information in table grade, thereby establishing a connection between the data in the two tables.

After the outer key is attracted, the outer key column can only insert the values ​​of the reference column. The value of the reference column cannot be deleted.

2. Add foreign key constraints to the table

If you want to truly connect the data of two tables, you need to add foreign key constraints to the table. The syntax format for adding foreign key constraints to a table is as follows: alter table table name add constraint FK_ID foreign key (foreign key field name) references foreign key table name (primary key field name)

When adding foreign key constraints to a table, there are some things that need to be noted, as follows:

(1) The table to establish a foreign key must be of InnoDB type, not Temporary tables. Because only InnoDB type tables in MySQL support foreign keys;

(2) When defining foreign key names, quotation marks cannot be added, such as constraint ‘FK_ID’ or constraint “FK_ID”, which are both wrong.

When the data in the main table is deleted, the data in the slave table should also be deleted, otherwise a lot of meaningless junk data will be generated. Mysql can add on delete or on update clauses when creating foreign keys to tell the database how to avoid the generation of garbage data. The specific syntax format is as follows:

Alter table table name addconstraint FK_ID foreign key (foreign key field name) references external table name (primary key field name);

[on delete{cascade | set null | no action | restrict}]

[on update{cascade | set null | no action | restrict}]

The specific description of each parameter in the statement is as shown in the following table:

Parameter nameCascadeSet nullNo action##Restrict

Function description

Delete all records that contain references to the deleted key value

Modify all records that contain references to the deleted key values ​​and replace them with null values ​​(cannot be used for fields that have been marked as not null)

No action

Reject the main table to delete or modify the foreign key associated column. (This is the default setting and the safest setting when the on delete and on update clauses are not defined)

3. Delete foreign key constraints: alter table table name drop foreign key foreign key name;


2. Operation of association table

1. Association relationship

(1) Many-to-one: In the many-to-one table relationship, The foreign key should be built on the most side, otherwise it will cause data redundancy.

(2) Many-to-many: such as student table and course schedule. Usually, in order to realize this relationship, an intermediate table (called a join table) needs to be defined. This table will have two foreign keys, referencing the course schedule and the student table respectively. In a many-to-many relationship, it should be noted that the two foreign keys connecting the table are repeatable, but the relationship between the two foreign keys cannot be repeated, so the two foreign keys are the same as those of the table. Union primary key.

(3) One-to-one: First of all, the master-slave relationship must be distinguished. The slave table requires the existence of the master table to be meaningful. For example, the person is the master table, the ID card is the slave table, and the foreign key is established in the slave table. It should be noted that this relationship is not common in databases, because information stored in this way is usually placed in a table. In actual development, the one-to-one association relationship can be applied in the following aspects.

Ø Split a table with many columns;

Ø Isolate part of a table for security reasons;

Ø Save temporary data and can be deleted effortlessly This table deletes the data.

2. Adding data

After the above statement is successfully executed, the data between the two tables will be related. sex. If you want to query the students in Software Class 1, you must first query the ID of Software Class 1, and then query the students in the student table based on this ID.


#3. Deleting data: Due to the relationship between the grade table and the student table, the referenced value of the reference column cannot be deleted. Therefore, when deleting a software class, be sure to delete all students in the class first, and then delete the class.

(1) Delete all students in Software Class 1

(2) In the grade table, delete Software Class 1

                                                                                                                                                                                                                               forwarding to deleting Software Class 2, will result in an error:

It should be noted that in actual situations, if you want to delete 'Software Class 1' There is no need to delete 'Students of Software Class 1'. You can change gid=1 in the student table to gid=null. As long as the column in the main table is not referenced by the slave table, it can be deleted. However, when creating the table, the gid field has a non-null constraint, so in this example only students can be deleted.

3. Connection query: When there are fields with the same meaning in two or more tables, you can use these fields to perform connection queries on different tables.

1. Cross connection: The returned result is the Cartesian product of all data rows in the two tables being connected, that is, the number of data rows in the first table that meet the query conditions is returned multiplied by the second The number of data rows in the table that meet the query conditions. The syntax format is as follows:

Select * from table 1 cross join table 2;






From the above results you can It can be seen that the result of the cross connection is the combination of all the data in the two tables. It should be noted that in actual research and development, this requirement is rare and is generally not used. Instead, specific conditions are used to perform the data Purposeful inquiry.

2. Inner connection: also known as simple connection or natural connection. Use comparison operators to compare the data of the two tables, and list the data rows that match the join conditions and combine them into new records. The syntax format is as follows:

Select query field from table 1 [inner] join table 2 on table 1. relational field = table 2. relational field

You can also use where conditional statements to achieve this Same functionality.

Although the query results of these two methods are the same, inner join is an inner join statement, and where is a conditional judgment statement. You can add other conditions directly after where. The inner join statement cannot.

#If the two tables involved in a join query are the same table, this query is called a self-join query. Self-join is a special kind of join. It means that the tables connected to each other are physically the same table, but logically divided into two tables. For example, if you want to query which employees are in Wang Hong’s department, you can use self-join query. .

3. Outer connection: The table on the left of the keyword is called the coordinates, and the word on the right is called the right table

Select the field to be queried from table 1 left|right [outer] join table 2

On table 1. relationship field = table 2. relationship field where condition

(1) left join (left join): return includes the left table All records in and the records in the right table that meet the join conditions.

If a record in the left table does not exist in the right table, it will be displayed as empty in the right table.

(2) Right join: Returns all records in the right table and records in the left table that meet the join conditions.

4. Compound conditional connection query

4. Subquery: refers to a query statement nested in another A query within a query statement. It can be nested in a select, select...into statement, insert...into and other statements. When executing a query statement, the statements in the subquery will first be executed, and then the returned results will be used as filter conditions for the outer query. In the subquery, you can usually use the in, exists, any, and all operators

( 1) Subquery with in keyword: The inner query statement only returns one data column, and the value in this data column will be used for comparison operation by the outer query statement.

For example: Query the department with employees whose age is 20 years old.

(2) Subquery with exists keyword: The parameter after the exists keyword can be any subquery. The function of this subquery is equivalent to testing. It does not Any data will be generated and only True or False will be returned. When the return value is True, the outer query will be executed.

In the following example, the return result of the subquery is True, so the outer query statement will be executed, that is, all department information is queried. It should be noted that the exists keyword is more efficient than the in keyword, so in actual development, especially when the amount of data is large, it is recommended to use the exists keyword.

(3) Subquery with any keyword: any means that any one of the conditions is met. It allows the creation of an expression to compare the return value list of the subquery. As long as any comparison condition in the inner subquery is met, a result is returned as the outer query condition.

(4) Subquery with all keyword: It is similar to any, except that the results returned by the subquery with all keyword must satisfy all inner queries at the same time condition.

(5) Subquery with comparison operator

This article explains the multi-table operation of MySQL database, and more For more related content, please pay attention to php Chinese website.

Related recommendations:

$Selector--how to encapsulate DOM into jquery objects

Native js componentization Develop simple carousel chart example code

css3 animated navigation bar 3D

The above is the detailed content of MySQL database multi-table operation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

See all articles