Constraint design and association relationship design of Mysql table

https://blog.csdn.net/u012750578/article/details/15026677

Constraint design and association relationship design of Mysql table

=======================Table Integrity =======================

  (1) Entity integrity: each record has a unique identifier, usually represented by a field without any business meaning (primary key)

  (2) Referential integrity: a field in one table must reference a field value in another table (foreign key)

  (3) Domain integrity: The domain is the unit data, and the values ​​in the domain must conform to certain rules

Define primary key constraints

  primary key: not allowed to be empty, not allowed to repeat

Delete the primary key: alter table tablename drop primary key ;

 

Define the automatic growth of the primary key (id, no business meaning)

    auto_increment (MySQL specific/UUID class generation)

define unique constraints

  unique

define not-null constraints

  not null

Define foreign key constraints

constraint ordersid_FKforeign key(ordersid) references orders(id),

2 key concept

  (1) Primary key: only unique fields

  (2) Combined primary key: a combination of multiple fields to form a unique field

  (3) Foreign keys: for associations between multiple tables

 

3 Characteristics of the primary key

  (1) The primary key cannot be repeated

  (2) The primary key cannot be NULL

  (3) auto_increment is unique to MySQL. It starts from 1 by default, and the ID value lives and dies at the same time as the table.

  (4) In multi-person projects, UUID is usually used to generate a unique primary key value, which is convenient for maintaining entity integrity when multiple data are merged

--id primary key

mysql> create table teacher(id intprimary key,

   -> name varchar(20),

   -> brithday date);

Query OK, 0 rows affected (0.61 sec)

 

mysql> select * from teacher;

Empty set (0.00 sec)

 

mysql> insert into teachervalues(1,'jack','1992-2-12');

Query OK, 1 row affected (0.11 sec)

 

mysql> select * from teacher;

+----+------+------------+

| id | name | brithday   |

+----+------+------------+

|  1| jack | 1992-02-12 |

+----+------+------------+

1 row in set (0.00 sec)

 

mysql> desc teacher;

+----------+-------------+------+-----+---------+-------+

| Field   | Type        | Null | Key |Default | Extra |

+----------+-------------+------+-----+---------+-------+

| id      | int(11)     | NO   | PRI | NULL    |      |

| name    | varchar(20) | YES  |     | NULL   |       |

| brithday | date        | YES |     | NULL    |      |

+----------+-------------+------+-----+---------+-------+

3 rows in set (0.00 sec)

--The primary key cannot be repeated, the primary key conflicts, 1 represents the first column, that is, the id column

mysql> insert into teachervalues(1,'marry','1996-2-12');

ERROR 1062 (23000): Duplicate entry '1' forkey 'PRIMARY'

mysql>

-- Primary key cannot be null

mysql> insert into teachervalues(null,'marry','1996-2-12');

ERROR 1048 (23000): Column 'id' cannot benull

-- delete the primary key, there is only one primary key in the table, either one column or multiple columns

mysql> alter table teacher drop primarykey;

Query OK, 1 row affected (2.13 sec)

Records: 1 Duplicates: 0  Warnings: 0

 

mysql> desc teacher;

+----------+-------------+------+-----+---------+-------+

| Field   | Type        | Null | Key |Default | Extra |

+----------+-------------+------+-----+---------+-------+

| id      | int(11)     | NO   |    | NULL    |       |

| name    | varchar(20) | YES  |     | NULL   |       |

| brithday | date        | YES |     | NULL    |      |

+----------+-------------+------+-----+---------+-------+

3 rows in set (0.01 sec)

--The primary key id is automatically incremented

mysql> drop table if exists teacher;

Query OK, 0 rows affected (0.32 sec)

mysql> create table teacher(id intprimary key auto_increment,

   -> name varchar(20),

   -> birthday date);

Query OK, 0 rows affected (0.96 sec)

mysql> desc teacher;

+----------+-------------+------+-----+---------+----------------+

| Field   | Type        | Null | Key |Default | Extra          |

+----------+-------------+------+-----+---------+----------------+

| id      | int(11)     | NO   | PRI | NULL    | auto_increment |

| name    | varchar(20) | YES  |     | NULL   |                |

| birthday | date        | YES |     | NULL    |                |

+----------+-------------+------+-----+---------+----------------+

3 rows in set (0.01 sec)

mysql> insert into teacher(name,birthday)values('jack','1992-02-12');

Query OK, 1 row affected (0.06 sec)

 

mysql> insert intoteacher(name,birthday) values('marry','1992-4-8');

Query OK, 1 row affected (0.09 sec)

 

mysql> insert intoteacher(name,birthday) values('arry','1982-4-8');

Query OK, 1 row affected (0.14 sec)

 

mysql> select * from teacher;

+----+-------+------------+

| id | name | birthday   |

+----+-------+------------+

|  1| jack  | 1992-02-12|

|  2| marry | 1992-04-08 |

|  3| arry  | 1982-04-08|

+----+-------+------------+

3 rows in set (0.00 sec)

--Check the sequence of primary key id growth

mysql> delete from teacher whereid<=3;

Query OK, 3 rows affected (0.08 sec)

 

mysql> select * from teacher;

Empty set (0.00 sec)

 

mysql> insert intoteacher(name,birthday) values('jack','1992-02-12');

Query OK, 1 row affected (0.13 sec)

 

mysql> select * from teacher;

+----+------+------------+

| id | name | birthday   |

+----+------+------------+

|  4| jack | 1992-02-12 |

+----+------+------------+

1 row in set (0.00 sec)

--In multi-person projects, UUID is usually used to generate a unique primary key value, which is convenient for maintaining entity integrity when multiple data are merged

 

4 Features of Unique Constraint

  (1) Non-NULL values ​​cannot be repeated

  (2) Multiple NULL values ​​can be inserted

  (3) 'NULL' empty string and NULL are different concepts

mysql> drop table teacher;

Query OK, 0 rows affected (0.42 sec)

--only

mysql> create table teacher(id intprimary key auto_increment,

   -> name varchar(20) unique,

   -> birthday date);

Query OK, 0 rows affected (1.49 sec)

 

mysql> insert intoteacher(name,birthday) values('marry','2011-2-2');

Query OK, 1 row affected (0.11 sec)

 

mysql> insert intoteacher(name,birthday) values(NULL,'2011-1-1');

Query OK, 1 row affected (0.04 sec)

 

mysql> desc teacher;

+----------+-------------+------+-----+---------+----------------+

| Field   | Type        | Null | Key |Default | Extra          |

+----------+-------------+------+-----+---------+----------------+

| id      | int(11)     | NO   | PRI | NULL    | auto_increment |

| name    | varchar(20) | YES  | UNI | NULL   |                |

| birthday | date        | YES |     | NULL    |                |

+----------+-------------+------+-----+---------+----------------+

3 rows in set (0.00 sec)

-- violate the unique

mysql> insert intoteacher(name,birthday) values('marry','2011-2-2');

ERROR 1062 (23000): Duplicate entry 'marry'for key 'name'

5 Characteristics of non-null constraints

  (1) NULL values ​​cannot be inserted

  (2) Primary key constraint = non-NULL constraint + unique constraint

-- violates the not-null constraint

mysql> drop table if exists teacher;

Query OK, 0 rows affected (0.19 sec)

 

mysql> create table teacher(

   ->    id int primary keyauto_increment,

   ->    name varchar(20) not nullunique,

   ->    birthday date

   -> );

Query OK, 0 rows affected (1.45 sec)

 

mysql> insert intoteacher(name,birthday) values(NULL,'2011-1-1');

ERROR 1048 (23000): Column 'name' cannot benull

6 External health features

  (1) The foreign key value must come from the primary key value of another table referenced, or NULL

  

*7 Relationship

  (1) One-to-one (related to Waijiangen's business) 

  (2) One-to-many or many-to-one (foreign keys are placed in multiple parties)

  (3) Many-to-many (the external key is placed in the association table, that is, one many-to-many is split into two one-to-many relationships)

One-to-one relationship one:

mysql> create table person(

   ->  id int primary keyauto_increment,

   ->  name varchar(20) not null

   -> );

Query OK, 0 rows affected (1.16 sec)

mysql> insert into person(name)values('jack');

Query OK, 1 row affected (0.15 sec)

 

mysql> insert into person(name)values('marry');

Query OK, 1 row affected (0.06 sec)

-- pid in card is the foreign key of foreign person

mysql> create table card(

    -> id int primary key auto_increment,

   ->  location varchar(20) notnull,

   ->  pid int,

   ->  constraint pid_FK foreignkey(pid) references person(id)

   -> );

Query OK, 0 rows affected (1.55 sec)

mysql> insert into card(location,pid)values('BJ',1);

Query OK, 1 row affected (0.11 sec)

 

mysql> insert into card(location,pid)values('GZ',2);

Query OK, 1 row affected (0.39 sec)

--Foreign key pid can insert NULL

mysql> insert into card(location,pid)values('CS',NULL);

Query OK, 1 row affected (0.05 sec)

--Display the data in the person and card tables

mysql> select * from person;

+----+-------+

| id | name |

+----+-------+

|  1| jack  |

|  2| marry |

+----+-------+

2 rows in set (0.00 sec)

 

mysql> select * from card;

+----+----------+------+

| id | location | pid  |

+----+----------+------+

|  1| BJ       |    1 |

|  2| GZ       |    2 |

|  3| CS       | NULL |

+----+----------+------+

3 rows in set (0.00 sec)

--Error when inserting pid of 3, the foreign key pid must originate from the primary key value of another table or be NULL

mysql> insert into card(location,pid)values('NJ',3);

ERROR 1452 (23000): Cannot add or update achild row: a foreign key constraint fails (`mydb2`.`card`, CONSTRAINT `pid_FK`FOREIGN KEY (`pid`) REFERENCES `person` (`id`))

Note: The foreign key value must come from the primary key value of another table referenced, or NULL  

-- A row with a foreign key relationship cannot be deleted. It is necessary to delete its associated foreign key relationship first, and then delete the data of the primary key relationship, which is the opposite of when it was created.      

mysql> deletefrom person where name='jack';

ERROR 1451(23000): Cannot delete or update a parent row: a foreign key constraint fails(`mydb2`.`card`, CONSTRAINT `pid_FK` FOREIGN KEY (`pid`) REFERENCES `person`(`id`))

One-to-one relationship mode 2: The primary key is used as a foreign key to another table

For example, the id of the card table below is both a primary key and a foreign key

mysql> drop table if exists card;

Query OK, 0 rows affected (0.22 sec)

 

mysql> drop table if exists person;

Query OK, 0 rows affected (0.22 sec)

 

mysql> create table person(

    -> id int primary key auto_increment,

   ->  name varchar(20) not null

   -> );

Query OK, 0 rows affected (0.90 sec)

 

mysql> insert into person(name)values('jack');

Query OK, 1 row affected (0.07 sec)

 

mysql> insert into person(name)values('marry')

   -> ;

Query OK, 1 row affected (0.10 sec)

-- use primary key as foreign key

mysql> create table card(

   ->  id int primary keyauto_increment,

   ->  location varchar(20) notnull,

   ->  constraint id_FK foreignkey(id) references person(id)

   -> );

Query OK, 0 rows affected (0.86 sec)

 

mysql> insert into card(location)values('BJ');

Query OK, 1 row affected (0.06 sec)

mysql> insert into card(location)values('CS');

Query OK, 1 row affected (0.18 sec);

--id is 3, does not meet referential integrity, 3 cannot be hit in the person table

mysql> insert into card(location) values('GZ');

ERROR 1452 (23000): Cannot add or update achild row: a foreign key constraint fails (`mydb2`.`card`, CONSTRAINT `id_FK`FOREIGN KEY (`id`) REFERENCES `person` (`id`))

--NULL doesn't work either, because here id is a non-null attribute

mysql> insert into card(location)values(NULL);

ERROR 1048 (23000): Column 'location'cannot be null

===========================One-to-many relationship ===================== =========

Design:

One party makes a container, and multiple parties make a reference

mysql> create table department(

   ->  id int primary keyauto_increment,

   ->  name varchar(20) not null

   -> );

Query OK, 0 rows affected (1.70 sec)

 

mysql> insert into department(name)values('software department');

Query OK, 1 row affected (0.10 sec)

 

mysql> insert into department(name)values('Sales Department');

Query OK, 1 row affected (0.06 sec)

 

mysql> create table employee(

   ->  id int primary keyauto_increment,

   ->  name varchar(20) not null,

   ->  did int,

   ->  constraint did_FK foreignkey(did) references department(id)

   -> );

Query OK, 0 rows affected (1.02 sec)

 

mysql> insert into employee(name,did)values('jack',1);

Query OK, 1 row affected (0.12 sec)

 

mysql> insert into employee(name,did)values('marry',1);

Query OK, 1 row affected (0.13 sec)

 

mysql>

 

mysql> select * from department;

+----+-----------+

| id | name      |

+----+-----------+

| 1| Software Department |

| 2| Sales Department |

+----+-----------+

2 rows in set (0.00 sec)

 

mysql> select * from employee;

+----+-------+------+

| id | name | did  |

+----+-------+------+

|  1| jack  |    1 |

|  2| marry |    1 |

+----+-------+------+

2 rows in set (0.00 sec)

--Query the employees of the software department (using subqueries)

mysql> select * from employee wheredid=(select id from department where name='软件部');

+----+-------+------+

| id | name | did  |

+----+-------+------+

|  1| jack  |    1 |

|  2| marry |    1 |

+----+-------+------+

2 rows in set (0.05 sec)

--Using multi-table query

mysql> select e.name as employee name, d.name as department name from employee e, department d where d.name='software department';

+--------------+--------------+

| Employee Name | Department Name |

+--------------+--------------+

| jack | Software Department |

| marry | Software Department |

+--------------+--------------+

2 rows in set (0.01 sec)

=============================Many-to-many scheme =================== ===========

--When creating, first create both sides, and then create the middle

--When deleting, delete the middle first, then delete the two sides

mysql> drop table if exists middle;

Query OK, 0 rows affected, 1 warning (0.00sec)

 

mysql> drop table if exists student;

Query OK, 0 rows affected (0.25 sec)

 

mysql> drop table if exists teacher;

Query OK, 0 rows affected (0.33 sec)

 

mysql> create table if not existsstudent(

   ->  id int primary keyauto_increment,

   ->  name varchar(20) not null

   -> );

Query OK, 0 rows affected (1.19 sec)

 

mysql> insert into student(name)values('jack');

Query OK, 1 row affected (0.08 sec)

 

mysql> insert into student(name)values('marry');

Query OK, 1 row affected (0.04 sec)

 

mysql> create table if not existsteacher(

    ->  id int primary key auto_increment,

   ->  name varchar(20) not null

   -> );

Query OK, 0 rows affected (1.43 sec)

 

mysql> insert into teacher(name)values('赵');

Query OK, 1 row affected (0.34 sec)

 

mysql> insert into teacher(name)values('蔡');

Query OK, 1 row affected (0.07 sec)

--Many-to-many (the foreign key is placed in the association table, that is, splitting one many-to-many into two one-to-many relationships)

-- composite primary key

mysql> create table if not existsmiddle(

   ->  sid int,

   -> time int,

   ->  constraint sid_FK foreignkey(sid) references student(id),

   ->  constraint tid_FK foreignkey(tid) references teacher(id),

   ->  primary key(sid,tid)

   -> );

Query OK, 0 rows affected (1.59 sec)

mysql> insert into middle(sid,tid)values(1,1);

Query OK, 1 row affected (0.14 sec)

 

mysql> insert into middle(sid,tid)values(1,2);

Query OK, 1 row affected (0.06 sec)

 

mysql> insert into middle(sid,tid)values(2,1);

Query OK, 1 row affected (1.07 sec)

mysql> insert into middle(sid,tid)values(2,2);

Query OK, 1 row affected (0.07sec)mysql> insert into middle(sid,tid) values(2,2);

--Query all the students taught by Teacher Zhao, combined query

--t.name='Zhao' condition

-- and m.sid=s.id andm.tid=t.id -- join the tables

model:

select lists the fields that need to be displayed

from lists all the tables involved, it is recommended to write aliases

where business condition and table association condition

--sql

mysql> selectt.name as teacher, s.name as student

    -> from teacher as t,student as s,middleas m

    -> where t.name = '赵'and m.sid=s.id and m.tid=t.id;

+--------+--------+

| teacher | student |

+--------+--------+

| Zhao | jack |

| Zhao | marry |

+--------+--------+

2 rows in set(0.00 sec)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325944485&siteId=291194637