こんな感じでしょうか。
テーブル定義
sql
1create table rosen (
2 rosen_id int primary key,
3 rosen_name varchar(255)
4);
5
6create table bukken (
7 bukken_id int primary key,
8 bukken_name varchar(255),
9 rosen1 int references rosen (id),
10 rosen2 int references rosen (id),
11 rosen3 int references rosen (id)
12);
13
14insert into rosen values (1, '路線A');
15insert into rosen values (2, '路線B');
16insert into rosen values (3, '路線C');
17insert into rosen values (4, '路線D');
18
19insert into bukken values (1, '物件A', 1, 2, 3);
20insert into bukken values (2, '物件B', 1, 2, null);
21insert into bukken values (3, '物件C', 2, null, null);
問い合わせ
sql
1select rosen_id, rosen_name, count(bukken_id) as bukken_count
2 from (
3 select rosen_id, rosen_name, bukken_id
4 from rosen left outer join bukken on rosen_id = bukken.rosen1
5 union
6 select rosen_id, rosen_name, bukken_id
7 from rosen left outer join bukken on rosen_id = bukken.rosen2
8 union
9 select rosen_id, rosen_name, bukken_id
10 from rosen left outer join bukken on rosen_id = bukken.rosen3
11 ) t
12 group by rosen_id, rosen_name;
結果
+----------+------------+--------------+
| rosen_id | rosen_name | bukken_count |
+----------+------------+--------------+
| 1 | 路線A | 2 |
| 2 | 路線B | 3 |
| 3 | 路線C | 1 |
| 4 | 路線D | 0 |
+----------+------------+--------------+
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/08/12 07:01