まずはそれぞれのテーブルの定義とレコードの確認です。
person テーブル
MariaDB [test]> desc person;+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(30) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
| gender | smallint(2) | YES | | NULL | |
| dept_no | int(11) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
MariaDB [test]> select * from person;+----+-------+------+--------+---------+
| id | name | age | gender | dept_no |
+----+-------+------+--------+---------+
| 1 | kai | 27 | 1 | 1 |
| 2 | gerda | 25 | 2 | 2 |
| 3 | ragi | 33 | 1 | 1 |
+----+-------+------+--------+---------+
department テーブル
MariaDB [test]> desc department;+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| no | int(11) | NO | PRI | NULL | |
| name | varchar(30) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
MariaDB [test]> select * from department;+----+-------------------+
| no | name |
+----+-------------------+
| 1 | sales |
| 2 | human resource |
+----+-------------------+
まずは person テーブルと department テーブルの全列を表示してみましょう。
WHERE 句により、person テーブルの dept_no 列と department テーブルの no 列を結合しています。
MariaDB [test]> SELECT * FROM person, department WHERE person.dept_no = department.no;+----+-------+------+--------+---------+----+-------------------+
| id | name | age | gender | dept_no | no | name |
+----+-------+------+--------+---------+----+-------------------+
| 1 | kai | 27 | 1 | 1 | 1 | sales |
| 2 | gerda | 25 | 2 | 2 | 2 | human resource |
| 3 | ragi | 33 | 1 | 1 | 1 | sales |
+----+-------+------+--------+---------+----+-------------------+
続いて、表示する列を絞ってみましょう。person テーブル、department テーブルの name 列のみを表示してみます。
MariaDB [test]> SELECT person.name, department.name FROM person, department WHERE person.dept_no = department.no;+-------+-------------------+
| name | name |
+-------+-------------------+
| kai | sales |
| gerda | human resource |
| ragi | sales |
+-------+-------------------+
0 件のコメント:
コメントを投稿