Relationship between tables and tables Single-table query Multi-table query 055

Relationship between tables and tables Single-table query Multi-table query 055

1. The relationship between the table and the table --- a variant of the foreign key



  One-to-many or many-to-one Many-to-many One-to-one

  Find the relationship between two tables

    Analysis steps:

      # 1 First stand at the angle of the left table to find

        Whether multiple records in the left table can correspond to a record in the right table, if so, prove a field in the left table

      A field in the right table of foreign key

      # 2 Then look for it from the angle of the right table

        Whether multiple records in the right table can correspond to one record in the left table, if so, prove a field in the right table

      A field of foreign key coordinates

      # 3 Summary: 

        # many to one

          If only step 1 is established, the left table is many-to-one and the right table

          If only step 2 is established, the right table is many-to-one left table

        # many to many

          The establishment of steps 1 and 2 at the same time proves that the two tables are a two-way many-to-one or many-to-many, which requires

          Define a relationship table between these two tables to specifically store the relationship between the two tables

        # one to one

          1 and 2 are not true, but a record in the left table uniquely corresponds to a record in the right table, and vice versa

           This situation is very simple, that is, on the basis of the left table foreign key right table, the foreign key of the left table

          The field can be set to unique

        Many-to-one relationship: For example, a publishing house can publish multiple books 

        Association method: foreign key

# 创建主表
create table press(
    id int primary key auto_increment,
    name varchar(20)
);
# 创建从表
create table book(
    id int primary key auto_increment,
    name varchar(20),
    press_id int not null,
        constraint fk_book_press foreign key(press_id) references press(id)
    on delete cascade 
    on  update  cascade , 
); 
# First insert into the associated table 
insert  into press(name) values 
​​( ' Beijing Industrial Landmine Publishing House ' ), 
( ' People's Music Is Not Good Publishing House ' ), 
( ' Intellectual property rights are useless Publishing House ' ); 
# Insert records into the association table 
insert  into book(name,press_id) values 
​​( ' Jiuyang Shengong ' , 1 ), 
( ' Nine Yin Scriptures ' , 2 ), 
( ' Nine Yin White Bone Claws ' ,2 ), 
( ' Nine Swords of Dugu ' , 3 ), 
( ' Ten Slaps of Subduing the Dragon ' , 2 ), 
( ' Sunflower Collection ' , 3 )

Query result: 
mysql> select * from book; 
+----+-----------------+----------+ 
| id | name | press_id | 
+----+-----------------+----------+ 
| 1 | Nine Suns | 1 | 
| 2 | Nine Yin Scripture| 2 | 
| 3 | Nine Yin White Bone Claws| 2 | 
| 4 | Dugu 
Nine 
Swords| 3 | 
| 5 | ----------------+----------+ 
6 rows in set (0.00 sec) 

mysql> select * from press; 
+----+- -------------------------------+ 
| id | name | 
+----+------- -------------------------+ 
| 1 | Beijing Industrial Landmine Publishing House| 
| 2 | People's Music Is Not Good Publishing House|
| 3 | Intellectual property is useless Press| 
+----+--------------------------------+ 
3 rows in set (0.00 sec)

        Many-to-many relationship (relationship between authors and books)

          Many-to-many: An author can write multiple books and a book can also have multiple authors, bidirectional one-to-many,

        That is, many-to-many association method: foreign key + a new table

     One-to-one relationship between users and blogs, a user can only register one blog

      Association method: foreign key + unique

# For example, a user can only register one blog 
# Two tables: user table ( user ) and blog table (blog) 
# Create user table 
create  table  user ( 
    id int  primary  key auto_increment, 
    name varchar ( 20 ) 
); 
# Create blog table 
create  table blog( 
    id int  primary  key auto_increment, 
    url varchar ( 100 ),
     user_id  int  unique ,
     constraint fk_user foreign  key ( user_id) references  user (id)
     on  delete  cascade 
    on  update  cascade 
); 
# Insert records into user table 
insert  into  user (name) values 
​​( ' alex ' ), 
( ' wusir ' ), 
( ' egon ' ), 
( ' xiaoma ' ); 
# Insert record into blog table 
insert  into blog(url, user_id ) values 
​​( ' http://www.cnblog/alex ' ,1),
('http://www.cnblog/wusir',1),
('http://www.cnblog/egon',1),
('http://www.cnblog/xiaoma',1),

Single table query:


 

1. Syntax of single table query
     select field 1, field 2,... from table name
                 where condition
                 group  by field
                 having filter condition
                 order  by field 
                limit limit the number of entries 
2. Keyword execution priority (emphasis) 
    Keyword execution Priority 
    from  
    where 
    group  by 
    having 
    select 
    distinct 
    order  by 
    limit 
    
    1. Find the table: from 
    2. With the constraints specified by where, go to the file / table to take out records
     3. Group the taken out records by group  byIf there is no group  by , the whole as a group
     4. Filter the grouped results by having
     5. Execute select
     6. Remove duplicates
     7. Sort the results according to the conditions: order  by 
    8. Limit the number of displayed results, for example, only look at the first name
group by

group by happens after where, where condition is optional

Categorize on the same field

select * from employee group by post;

Note: After grouping, only the grouped fields can be obtained. If you want to obtain the information in the group, you need to calculate it through the aggregation function

 aggregate function
max () maximum value
 min () minimum value
 sum ()
 sum count () calculate the total number
 avg () calculate the average 
limit0,5 The first parameter indicates the starting position of the query The second parameter indicates the number of parameters to obtain The number    0 , 5 means to take the top five 2 , 5 means to take the 3-7 names group
 - concat (name) will display all the names in the selected conditions
virtual table
# Create an alias
 select   Aa from ( select post, count ( 1 )   as a from employee group  by post) as A 
uses the first filtered table as the main table for the second screening

having

mysql5.7 as a whole can execute sql as a group

select  *  from employee having salary > 1000000 ; 
without group, the entire form is grouped by default

mysql 5.6 5.5

mysql >   select  *  from employee having salary > 1000000 ; 
ERROR 1463 ( 42000 ): Non - grouping field ' salary '  is used in  HAVING clause 
# Must be grouped before using having

multi-table query

grammar:
select field list
     from table 1 inner  | left  | right  | join table 2
     on table 1. field = table 2. field
 
Multi-table join query
# Eligible query
 select   *  from employee,department where employee.dep_id = department.id;
inner join

 

Get only matching data

select * from employee inner join department on employee.dep_id = department.id;
left join or right join

 

Only display all records in the left or right table

select * from employee left join department on employee.dep_id = department.id;
full outer join

 
select * from employee left join department on employee.dep_id = department.id
  union
select * from employee right join department on employee.dep_id = department.id;
subquery

 
# 1 : A subquery is to nest a query statement within another query statement. 
# 2 : The query result of the inner query statement can provide query conditions for the outer query statement. 
# 3 : The subquery can contain: keywords such as IN , NOT  IN , ANY , ALL , EXISTS , and NOT EXISTS 
# 4 : It can also contain comparison operators: = , != , > , <, etc. #small exercise

#Query the name of the department whose average age is over 25 years old
select * from department where id in (select dep_id from employee group by dep_id having avg(age) > 25);

 

 

 
posted @ 2018-11-22 16:03 You are not as important as you think Read ( ... ) Comment ( ... ) Edit Favorites

Guess you like

Origin blog.csdn.net/bruce_van/article/details/89443049