MySQL foreign key definition method (1)

Source: Internet
Author: User

Foreign keys bring many benefits to MySQL. The following describes how to write statements for defining foreign keys in MySQL and how to handle errors when defining foreign keys in MySQL.

 
 
  1. mysql> CREATE TABLE categories (  
  2.       -> category_id tinyint(3) unsigned NOT NULL AUTO_INCREMENT,  
  3.       -> name varchar(30) NOT NULL,  
  4.       -> PRIMARY KEY(category_id)  
  5.       -> ) ENGINE=INNODB;  
  6. Query OK, 0 rows affected (0.36 sec)  
  7.  
  8. mysql> INSERT INTO categories VALUES (1, ‘SQL Server’), (2, ‘Oracle’), (3, ‘PostgreSQL’), (4, ‘MySQL’), (5, ‘SQLite’);  
  9. Query OK, 5 rows affected (0.48 sec)  
  10. Records: 5    Duplicates: 0    Warnings: 0  
  11.  
  12. mysql> CREATE TABLE members (  
  13.       -> member_id INT(11) UNSIGNED NOT NULL,  
  14.       -> name VARCHAR(20) NOT NULL,  
  15.       -> PRIMARY KEY(member_id)  
  16.       -> ) ENGINE=INNODB;  
  17. Query OK, 0 rows affected (0.55 sec)  
  18.  
  19. mysql> INSERT INTO members VALUES (1, ‘test’), (2, ‘admin’);  
  20. Query OK, 2 rows affected (0.44 sec)  
  21. Records: 2    Duplicates: 0    Warnings: 0  
  22.  
  23. mysql> CREATE TABLE articles (  
  24.       -> article_id INT(11) unsigned NOT NULL AUTO_INCREMENT,  
  25.       -> title varchar(255) NOT NULL,  
  26.       -> category_id tinyint(3) unsigned NOT NULL,  
  27.       -> member_id int(11) unsigned NOT NULL,  
  28.       -> INDEX (category_id),  
  29.       -> FOREIGN KEY (category_id) REFERENCES categories (category_id),  
  30.       -> CONSTRAINT fk_member FOREIGN KEY (member_id) REFERENCES members (member_id),  
  31.       -> PRIMARY KEY(article_id)  
  32.       -> ) ENGINE=INNODB;  
  33. Query OK, 0 rows affected (0.63 sec)  

Note: For non-InnoDB tables, the foreign key clause is ignored.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.