国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
##Usage of Mysql foreign keys" >##Usage of Mysql foreign keys
Details before use" >Details before use
In the existing table Add and delete foreign keys in " >In the existing table Add and delete foreign keys in
Operation of associated actions" >Operation of associated actions
Home Database Mysql Tutorial What is mysql foreign key

What is mysql foreign key

Apr 11, 2023 am 10:45 AM
mysql foreign key

mysql foreign key is a very useful data processing function that can quickly update data between tables; simply speaking, it can establish an association between two tables and perform operations When one table is updated, the data in the other table will also change simultaneously.

What is mysql foreign key

The operating environment of this tutorial: Windows 10 system, mysql8 version, Dell G3 computer.

What is mysql foreign key?

##Usage of Mysql foreign keys

Foreign key is a very, very easy-to-use thing, and it is also a function that many relational databases have. To put it simply, it can establish an association between two tables, which can be done when operating one table. , the data in another table will also change simultaneously.

Example:
一個學生表里面有學生的所有信息,其中有一個字段是班級id,又有一個班級表,記錄著所有的班級信息,按照邏輯來說,如果我們刪除了班級
表里面的某個班級,學生表里面是這個班級id的信息就應該修改。
The above example can be completed normally if we use a program. First delete the class, and then add it to the student table. The class id field of the student information of this class is modified and divided into two parts. But if we use foreign keys, it only takes one step. As long as one of the foreign keys is associated, the other one will be automatically updated. Obviously, this is more in line with the program. It is also easier

Details before use
    When selecting a storage engine for the database, you must choose a storage engine that adapts to foreign keys, such as the default storage of mysql Engine innodb
  1. The field types of related foreign key fields must be consistent. For example, the class_id of the student table is of type int, then the type of class_id of the class table should also be of type int. This is very important.
Create foreign key constraints in the new table
	create?table?stu_study?(
	??sid?int?primary?key?auto_increment,--?定義Sid??
??????sname?varchar(15)?not?null,
??????course_id?int?default?null,??--?定義課程id?課程id是外鍵所以要與關聯(lián)的主表的字段類型保持一致
??????constraint?stu_study_class?--?一個表里可能有多個表之間關聯(lián),所以外鍵需要起一個名字
??????foreign?key?(class_id)?--?關聯(lián)的外鍵名
??????references?classes(id)??--?關聯(lián)的主表和主表的字段
??????on?delete?cascade??--?當刪除的時候觸發(fā)
????)engine=InnoDB?default?charset?utf8??--?默認存儲引擎和編碼的字符串

What is mysql foreign key

In the existing table Add and delete foreign keys in
    Delete foreign keys
  1. ···
    – Delete foreign keys (foreign key constraints)
    alter table stu_study drop foreign key stu_study_classes;
    ···

    What is mysql foreign key Deleting a foreign key is done by deleting it based on the foreign key name in the table. This also indirectly lets us know that the foreign key name cannot be repeated.
  2. Add foreign key
  3. 	--?添加外鍵
    ??alter?table?stu_study?add
    ??constraint?stu_study_classes??--?外鍵名?是一定不能夠重復的,通常會用關聯(lián)的兩個表名進行命名
    ??foreign?key(course_id)
    ??references?classes(id)
    ??on?delete?cascade;

What is mysql foreign key Adding a foreign key to an existing table is very similar to adding a foreign key when creating a table. There are some details. That is, he needs to use the constraint foreign key name to set the name of the foreign key
We will find that adding and modifying foreign keys is very similar to adding and modifying table fields. The keywords used are add, drop, etc.

Operation of associated actions
Sub table


What is mysql foreign key Main table

What is mysql foreign key We can simply understand the word table and sub table as , the table with the foreign key set is the subtable
There are many kinds of related actions, such as
cascade, set Null, no action, all three It is to set the associated action when setting the foreign key. For example,
What is mysql foreign key represents the action performed when deleting. The main differences are as follows:

  1. cascade 刪除主表的某個字段的時候,子表含有這個字段的數(shù)據(jù)會被清空,這個還是屬于相對危險的一個操作的
  2. +set null 刪除主表的某個字段的時候,子表含有這個字段的這個哪一行的這個字段會用null來顯示,但是有個細節(jié)就是設置外鍵的這個字段字段類型就不能設置為not null類型的,否則會報錯
  3. no action 這個字段會比較有意思,也就是說當主表要刪除某個行的時候,如果外鍵關聯(lián)有含有這個主表的外鍵的字段數(shù)據(jù)的話,就不會刪除成功,系統(tǒng)會直接報錯
關聯(lián)更新操作

之前是主要講了關聯(lián)刪除,是因為外鍵在使用的時候關聯(lián)刪除操作是使用的比較頻繁的,關聯(lián)更新的頻率是相對來說低一點兒的
關聯(lián)更新的三個關聯(lián)操作和刪除時一樣的,分別是cascade,set null,no action意思是也是一樣的,主表某個字段更新了,子表也會更新那個字段!??!,主表更新的某條數(shù)據(jù),子表的使用的那個數(shù)據(jù)會變成空,和子表在使用的情況下,主表就不能夠更新數(shù)據(jù)

	alter?table?stu_study?drop?foreign?key?stu_study_classes;??--?刪除外鍵
	--?添加外鍵
	alter?table?stu_study?add?
????constraint?stu_study_classes?
????foreign?key?(course_id)?
????references?classes(id)?
????on?delete?set?null?--?一次性設置外鍵的兩種動作
????on?update?cascade

What is mysql foreign key
What is mysql foreign key

總結
  • 數(shù)據(jù)庫的外鍵是非常非常好用的一個技術,可以讓我們快速的進行表之間的數(shù)據(jù)的更新
  • 外鍵可以簡單的理解成會自動的替我們做一個數(shù)據(jù)變動的處理

推薦學習:《MySQL視頻教程

The above is the detailed content of What is mysql foreign key. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Performing logical backups using mysqldump in MySQL Performing logical backups using mysqldump in MySQL Jul 06, 2025 am 02:55 AM

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

Handling NULL Values in MySQL Columns and Queries Handling NULL Values in MySQL Columns and Queries Jul 05, 2025 am 02:46 AM

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

Aggregating data with GROUP BY and HAVING clauses in MySQL Aggregating data with GROUP BY and HAVING clauses in MySQL Jul 05, 2025 am 02:42 AM

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

Paginating Results with LIMIT and OFFSET in MySQL Paginating Results with LIMIT and OFFSET in MySQL Jul 05, 2025 am 02:41 AM

MySQL paging is commonly implemented using LIMIT and OFFSET, but its performance is poor under large data volume. 1. LIMIT controls the number of each page, OFFSET controls the starting position, and the syntax is LIMITNOFFSETM; 2. Performance problems are caused by excessive records and discarding OFFSET scans, resulting in low efficiency; 3. Optimization suggestions include using cursor paging, index acceleration, and lazy loading; 4. Cursor paging locates the starting point of the next page through the unique value of the last record of the previous page, avoiding OFFSET, which is suitable for "next page" operation, and is not suitable for random jumps.

Implementing Transactions and Understanding ACID Properties in MySQL Implementing Transactions and Understanding ACID Properties in MySQL Jul 08, 2025 am 02:50 AM

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Handling character sets and collations issues in MySQL Handling character sets and collations issues in MySQL Jul 08, 2025 am 02:51 AM

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

Calculating Database and Table Sizes in MySQL Calculating Database and Table Sizes in MySQL Jul 06, 2025 am 02:41 AM

To view the size of the MySQL database and table, you can query the information_schema directly or use the command line tool. 1. Check the entire database size: Execute the SQL statement SELECTtable_schemaAS'Database',SUM(data_length index_length)/1024/1024AS'Size(MB)'FROMinformation_schema.tablesGROUPBYtable_schema; you can get the total size of all databases, or add WHERE conditions to limit the specific database; 2. Check the single table size: use SELECTta

Setting up asynchronous primary-replica replication in MySQL Setting up asynchronous primary-replica replication in MySQL Jul 06, 2025 am 02:52 AM

To set up asynchronous master-slave replication for MySQL, follow these steps: 1. Prepare the master server, enable binary logs and set a unique server-id, create a replication user and record the current log location; 2. Use mysqldump to back up the master library data and import it to the slave server; 3. Configure the server-id and relay-log of the slave server, use the CHANGEMASTER command to connect to the master library and start the replication thread; 4. Check for common problems, such as network, permissions, data consistency and self-increase conflicts, and monitor replication delays. Follow the steps above to ensure that the configuration is completed correctly.

See all articles