JSON_ARRAYAGG (5.7.22 から導入) を用いて、
select id, agg->'$[*][0]' as tag_ids, agg->'$[*][1]' as tags from (
select b.id, JSON_ARRAYAGG(JSON_ARRAY(t.tag_id, t.tag)) as agg
FROM
blog AS b
LEFT JOIN blog_tag AS bt ON (b.id = bt.blog_id)
LEFT JOIN tag AS t ON (t.tag_id = bt.tag_id)
where b.id = 1
group by b.id
) as t;
とすることで、
+----+---------+------------+
| id | tag_ids | tags |
+----+---------+------------+
| 1 | [2, 5] | ["y", "x"] |
+----+---------+------------+
を得ます。
そして、自分でしたら、 json 配列を 2,5
などに整形する必要がある場合、それはアプリケーション側で実行すると思います。
もし、 blog_tag に重複エントリがある場合には、一回 distinct をかけます。具体的には:
select id, agg->'$[*][0]' as tag_ids, agg->'$[*][1]' as tags from (
select id, JSON_ARRAYAGG(JSON_ARRAY(tag_id, tag)) as agg
from (
select distinct b.id, t.tag_id, t.tag
FROM
blog AS b
LEFT JOIN blog_tag AS bt ON (b.id = bt.blog_id)
LEFT JOIN tag AS t ON (t.tag_id = bt.tag_id)
where b.id = 1
) as t
group by id
) as t;
ただ、ここまでだと tag に紐づかない blog については、
+----+---------+--------+
| id | tag_ids | tags |
+----+---------+--------+
| 3 | [null] | [null] |
+----+---------+--------+
が得られてしまいます。
8.0 以上の CTE を用いれば、以下のようにできます。
with target_id as ( select 3 ),
agg as (
select JSON_ARRAYAGG(JSON_ARRAY(tag_id, tag)) as agg
from (
select distinct b.id, t.tag_id, t.tag
FROM
blog AS b
INNER JOIN blog_tag AS bt ON (b.id = bt.blog_id)
INNER JOIN tag AS t ON (t.tag_id = bt.tag_id)
where b.id = (select * from target_id)
) as t
group by id
)
select (select * from target_id) as id,
coalesce(
(select agg->'$[*][0]' from agg),
JSON_ARRAY()
) as tag_ids,
coalesce(
(select agg->'$[*][1]' from agg),
JSON_ARRAY()
) as tags
+------+---------+------+
| id | tag_ids | tags |
+------+---------+------+
| 3 | [] | [] |
+------+---------+------+
以下、手軽に検証するための CTE
with blog as (
select 1 as id
union all
select 2 as id
union all
select 3 as id
), tag as (
select 2 as tag_id, 'y' as tag
union all
select 5, 'x'
union all
select 1, 'z'
), blog_tag as (
select 1 as blog_id, 2 as tag_id
union all
select 1 as blog_id, 2 as tag_id
union all
select 1 as blog_id, 5 as tag_id
union all
select 2 as blog_id, 1 as tag_id
),
-- 以下、実際のクエリ部分
target_id as ( select 3), -- ここを実際のプレースホルダにかえる
agg as (
select JSON_ARRAYAGG(JSON_ARRAY(tag_id, tag)) as agg
from (
select distinct b.id, t.tag_id, t.tag
FROM
blog AS b
INNER JOIN blog_tag AS bt ON (b.id = bt.blog_id)
INNER JOIN tag AS t ON (t.tag_id = bt.tag_id)
where b.id = (select * from target_id)
) as t
group by id
)
select (select * from target_id) as id,
coalesce(
(select agg->'$[*][0]' from agg),
JSON_ARRAY()
) as tag_ids,
coalesce(
(select agg->'$[*][1]' as tags from agg),
JSON_ARRAY()
) as tags;