MySQL--operation abbreviation (join table, combined query (UNION))

junction table

1. Create a link

SELECT vend_name,prod_name,prod_price
FROM vendors, products
WHERE vendors.vend_id = products.vend_id
  • 1
  • 2
  • 3

The biggest difference between the above statement and the previous one is that the specified column is located in the two tables and is joined using where.
Return the vend_name, prod_name, prod_price with the same vend_id in the table vendors and the products table

Based on an equality test between two tables, this join is called an equijoin, or inner join. For this kind of join, you can also use the following syntax:

  • INNER JOIN
    ON
SELECT vend_name,prod_name,prod_price
FROM vendors INNER JOIN products
 ON vendors.vend_id = products.vend_id
  • 1
  • 2
  • 3

2. Join multiple tables

SELECT vend_name,prod_name,prod_price, quantity
FROM vendors, products, order
WHERE vendors.vend_id = products.vend_id
AND order.prod_id = products.vend_id
AND order_num = 20005;
  • 1
  • 2
  • 3
  • 4
  • 5

FROM is followed by multiple tables, and the WHERE clause conditions are joined with AND.

3. Other types of joins

  • Self-join: referencing the same table more than once in a select statement
  • Natural join: at least one column is present in more than one table
  • Outer join: The join contains rows that have no associated rows in the related table

Combined query

Execute multiple queries (multiple SELECT statements) and return the results as a single query result set.

1. Create a combined query

  • UNION

    For example, I want to query the id number whose price is less than 10 or the supplier's name is a, that is, how can the following two statements be realized at the same time

SELECT order_id, order_price, order_name
FROM order1
WHERE order_price < 10;
  • 1
  • 2
  • 3
SELECT order_id, order_price, order_name
FROM order1
WHERE order_name = 'a';
  • 1
  • 2
  • 3

Use union combinations:

SELECT order_id, order_price, order_name
FROM order1
WHERE order_price < 10
UNION
SELECT order_id, order_price, order_name
FROM order1
WHERE order_name = 'a';
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

write picture description here

2. UNION rules

  • Must consist of two or more select statements, separated by a UNION
  • Each query in a UNION must contain the same column, expression or aggregate function
  • The column data types must be compatible, the types do not have to be exactly the same, but they must be implicitly convertible types
  • After using UNION to meet the conditions, there may be duplicates that meet the conditions, and there will be duplicates. Use UNION ALL to automatically remove duplicate rows

3. Sort the combined query results

When combining queries with UNION, only one ORDER BY clause can be used, which must appear after the last SELECT statement

Guess you like

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