GUI,CUIでレコードをいれる、Joinでテーブルを結合、order byで並び替え
作成したテーブルにレコードをいれていく
GUIではエクセルみたいにいれてApply押すだけ
CUIではINSERTで作成
mysql> show tables; +---------------------+ | Tables_in_demo | +---------------------+ | db_ex_item | | db_ex_order_detail | | db_ex_user | | dx_ex_order_detail2 | | inquiry | | inquiry3 | | item | +---------------------+ 7 rows in set (0.01 sec) mysql> INSERT INTO `demo`.`db_ex_item` (`name`, `manufacture`, `price`) VALUES ('pen', 'aoki', '500'); Query OK, 1 row affected (0.00 sec)
テーブル結合
以下の2つのテーブルを結合する
db_ex_userテーブル
id(主キー) | name | adress |
---|---|---|
1 | meo1 | xxx-ttt |
2 | meo2 | xxx-yyy |
3 | meo3 | xxx-uuu |
db_ex_order_detailテーブル
id(主キー) | order_no | item_id(外部キー) | quantity | user_id(外部キー) | buy_date |
---|---|---|---|---|---|
1 | 0001 | 1 | 2 | 1 | 2022/08/21 |
2 | 0002 | 2 | 4 | 2 | 2022/08/22 |
3 | 0003 | 3 | 44 | 3 | 2022/08/23 |
4 | 0004 | 1 | 5 | 3 | 2022/8/24 |
5 | 0004 | 5 | 5 | 9 | 2022/8/24 |
Join
SELECT カラム名1, カラム名2, ... FROM テーブル名1 joinテーブル名2 on 結合の条件
「db_ex_order_detailテーブルから全てのカラムを取得し、それに、demo.db_ex_order_detailテーブルのuser_idとdemo.db_ex_userテーブルのidを対応させた状態で、demo.db_ex_order_detailテーブルを結合させる」
実行結果
db_ex_userテーブルのidは3までしかなく、それに対応したdemo.db_ex_order_detailテーブルのuser_idが3のレコードしか結合されない。つまり、ベースとなるテーブルから、条件にマッチするレコードがないものは削除される。
mysql> SELECT * FROM demo.db_ex_order_detail join demo.db_ex_user on demo.db_ex_order_detail.user_id = demo.db_ex_user.id; +----+----------+---------+----------+---------+---------------------+----+------+---------+ | id | order_no | item_id | quantity | user_id | buy_date | id | name | address | +----+----------+---------+----------+---------+---------------------+----+------+---------+ | 1 | 0001 | 1 | 2 | 1 | 2022-08-01 00:00:00 | 1 | meo1 | xxx-ttt | | 2 | 0002 | 2 | 1 | 2 | 2022-08-02 00:00:00 | 2 | meo2 | xxx-yyy | | 3 | 0003 | 3 | 4 | 3 | 2022-08-03 00:00:00 | 3 | meo3 | xxx-uuu | | 4 | 0004 | 1 | 5 | 3 | 2022-08-04 00:00:00 | 3 | meo3 | xxx-uuu | +----+----------+---------+----------+---------+---------------------+----+------+---------+ 4 rows in set (0.01 sec)
order by
order byでカラムを並び替える
- ASC : 昇順(小さいもの順)
- DESC : 降順(大きいもの順)
SELECT * FROM demo.db_ex_item ORDER BY <オーダー対象カラム> ASC;
SELECT * FROM demo.db_ex_order_detail join demo.db_ex_user on demo.db_ex_order_detail.user_id = demo.db_ex_user.id join demo.db_ex_item on demo.db_ex_order_detail.item_id = demo.db_ex_item.id order by demo.db_ex_user.name asc;
カラム名が重複していない場合は省略できる
order by price asc;