[MySQL Must Know and Know (12)] [Join Table]

Previous: [MySQL Must Know and Know (11)] [Use Subquery]

+++++++++++++Start line++++++++++++++++

One, connection

Connection in the execution of data retrieval queries is an important operation that can be performed using SQL SELECT

1.1 Relationship table

Relationship: The tables are related to each other through some commonly used values.
Foreign key: A foreign key is a column in a table that contains the primary key value of another table. It defines the relationship between the two tables.
Scalability: adaptable Constantly increasing workload without failure

Two, create a connection

mysql> SELECT vend_name, prod_name, prod_price
    -> FROM vendors, products
    -> WHERE vendors.vend_id = products.vend_id
    -> ORDER BY vend_name, prod_name;

Insert picture description here

Fully qualified column name

When the quoted column may be ambiguous, you must use the fully qualified column name (table name and column name separated by a dot)

2.1 The importance of the WHERE clause

When joining two tables, each row in the first table is paired with each row in the second table. The WHERE clause serves as a filter condition, and it only contains rows that match the given condition.

Cartesian Product

The result returned by the table relationship without the join condition is the Cartesian product. The number of rows retrieved will be the number of rows in the first table multiplied by the number of rows in the second table

mysql> SELECT vend_name, prod_name, prod_price
    -> FROM vendors, products
    -> ORDER BY vend_name, prod_name;

Insert picture description here

Don't forget the WHERE clause

Ensure that all connections have a WHERE clause, otherwise MySQL will return much more data than it wants

2.2 Internal connection

mysql> SELECT vend_name, prod_name, prod_price
    -> FROM vendors INNER JOIN products
    -> ON vendors.vend_id = products.vend_id;

Insert picture description here

2.3 Join multiple tables

SQL does not limit the number of tables that can be joined in a SELECT statement

mysql> SELECT prod_name, vend_name, prod_price, quantity
    -> FROM orderitems, products, vendors
    -> WHERE products.vend_id = vendors.vend_id
    -> AND orderitems.prod_id = products.prod_id
    -> AND order_num = 20005;

Insert picture description here

+++++++++++++End line++++++++++++++++

Next:【MySQL Must Know and Know (13)】【Create Advanced Connection

Guess you like

Origin blog.csdn.net/qq_42893334/article/details/108814831