👻

【MySQL】CROSS JOINについて

2023/09/18に公開

次の2つのようなテーブルがあった時に全てのパターンを表示するコマンドらしい。
使い道不明。シンプルにすべてのパターンの総数を導き出したい時とか?

customers

mysql> SELECT
    ->  *
    -> FROM customers;
id first_name last_name email
1 Boy George george@gmail.com
2 George Michael gm@gmail.com
3 David Bowie david@gmail.com
4 Blue Steele blue@gmail.com
5 Bette Davis bette@aol.com

orders

mysql> SELECT
    ->  *
    -> FROM orders;
id order_date amount customer_id
1 2016-02-10 99.99 1
2 2017-11-11 35.50 1
3 2014-12-12 800.67 2
4 2015-01-03 12.50 2
5 1999-04-11 450.25 5

CROSS JOIN結果

mysql> SELECT
    ->  *
    -> FROM customers
    -> CROSS JOIN orders;
id first_name last_name email id order_date amount customer_id
5 Bette Davis bette@aol.com 1 2016-02-10 99.99 1
4 Blue Steele blue@gmail.com 1 2016-02-10 99.99 1
3 David Bowie david@gmail.com 1 2016-02-10 99.99 1
2 George Michael gm@gmail.com 1 2016-02-10 99.99 1
1 Boy George george@gmail.com 1 2016-02-10 99.99 1
5 Bette Davis bette@aol.com 2 2017-11-11 35.50 1
4 Blue Steele blue@gmail.com 2 2017-11-11 35.50 1
3 David Bowie david@gmail.com 2 2017-11-11 35.50 1
2 George Michael gm@gmail.com 2 2017-11-11 35.50 1
1 Boy George george@gmail.com 2 2017-11-11 35.50 1
5 Bette Davis bette@aol.com 3 2014-12-12 800.67 2
4 Blue Steele blue@gmail.com 3 2014-12-12 800.67 2
3 David Bowie david@gmail.com 3 2014-12-12 800.67 2
2 George Michael gm@gmail.com 3 2014-12-12 800.67 2
1 Boy George george@gmail.com 3 2014-12-12 800.67 2
5 Bette Davis bette@aol.com 4 2015-01-03 12.50 2
4 Blue Steele blue@gmail.com 4 2015-01-03 12.50 2
3 David Bowie david@gmail.com 4 2015-01-03 12.50 2
2 George Michael gm@gmail.com 4 2015-01-03 12.50 2
1 Boy George george@gmail.com 4 2015-01-03 12.50 2
5 Bette Davis bette@aol.com 5 1999-04-11 450.25 5
4 Blue Steele blue@gmail.com 5 1999-04-11 450.25 5
3 David Bowie david@gmail.com 5 1999-04-11 450.25 5
2 George Michael gm@gmail.com 5 1999-04-11 450.25 5
1 Boy George george@gmail.com 5 1999-04-11 450.25 5

Discussion