A2-02-16.DML-A Practical Use of MySQL CROSS JOIN Clause

转载自:http://www.mysqltutorial.org/mysql-cross-join/

 

A Practical Use of MySQL CROSS JOIN Clause

 

Summary: in this tutorial, you will learn about the MySQL CROSS JOIN clause and how to apply it to answer some interesting data questions.

Introduction to MySQL CROSS JOIN clause

The CROSS JOIN clause returns the Cartesian product of rows from the joined tables.

Suppose you join two tables using CROSS JOIN. The result set will include all rows from both tables, where each row in the result set is the combination of the row in the first table with the row in the second table. This situation happens when you have no relationship between the joined tables.

The danger thing is that if each table has 1,000 rows, you will get 1,000 x 1,000 = 1,000,000 rows in the result set, which is huge.

The following illustrates the syntax of the CROSS JOIN clause that joins two tables T1 and T2:

Note that different from the INNER JOIN or LEFT JOIN clause, the CROSS JOIN clause does not have the join conditions.

If you add a WHERE clause, in case T1 and T2 has a relationship, the CROSS JOIN works like the INNER JOIN clause as shown in the following query:

 

MySQL CROSS JOIN clause example

We will use the following tables to demonstrate how the CROSS JOIN works.

There are three tables involved:

  1. The products table contains the products master data that includes product id, product name, and sales price.
  2. The stores table contains the stores where the products are sold.
  3. The sales table contains the products that sold in a particular store by quantity and date.

Suppose we have three products iPhoneiPad and Macbook Pro which are sold in two stores Northand South.

To get the total sales for each store and for each product, you calculate the sales and group them by store and product as follows:

MySQL CROSS JOIN GROUP BY example

Now, what if you want to know also which store had no sales of a specific product. The query above could not answer this question.

To solve the problem, you need to use the CROSS JOIN clause.

First, you use the CROSS JOIN clause to get the combination of all stores and products:

MySQL CROSS JOIN stores and products

Next, you join the result of the query above with the query that returns the total of sales by store and by product. The following query illustrates the idea(自己没有测试成功,可能是SQL模式的原因):

MySQL CROSS JOIN query example

Note that the query used the IFNULL function to return 0 if the revenue is NULL (in case the store had no sales).

By using the CROSS JOIN clause this way, you can answer a wide range of questions e.g., find the sales revenue by salesman by month even if a salesman had no sales in a particular month.

posted @ 2018-08-22 14:50  zhuntidaoren  阅读(161)  评论(0编辑  收藏  举报