とりあえずこんな感じでしょうか。(category と article は多対多にしてみました。)
https://www.db-fiddle.com/f/muBACYLE8v8UtVUNFGXzAL/0
データベース定義
sql
1create table article (
2 id int primary key,
3 title varchar(255),
4 user_id int
5);
6
7insert into article values (1, 'RubyonRailsに関する記事', 1);
8insert into article values (2, 'Javaに関する記事', 2);
9insert into article values (3, 'swiftに関する記事', 2);
10
11create table category (
12 id int primary key,
13 name varchar(255)
14);
15
16insert into category values (1, 'RubyonRails');
17insert into category values (2, 'Java');
18insert into category values (3, 'swift');
19
20create table category_article (
21 article_id int references article (id),
22 category_id int references category (id),
23 primary key (article_id, category_id)
24);
25
26insert into category_article values (1, 1);
27insert into category_article values (2, 2);
28insert into category_article values (3, 3);
29
30insert into category_article values (1, 3);
31insert into category_article values (3, 2);
問い合わせ
sql
1select
2category_article.article_id,
3category_article. category_id,
4article.user_id,
5(select count(*) from article a where a.user_id = article.user_id) as count
6from category_article
7left join article on category_article.article_id = article.id;
実行結果
+------------+-------------+---------+-------+
| article_id | category_id | user_id | count |
+------------+-------------+---------+-------+
| 1 | 1 | 1 | 1 |
| 1 | 3 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | 2 | 2 | 2 |
| 3 | 3 | 2 | 2 |
+------------+-------------+---------+-------+