回答編集履歴

2

ed

2022/09/24 19:54

投稿

m.ts10806
m.ts10806

スコア80850

test CHANGED
@@ -58,7 +58,7 @@
58
58
 
59
59
  -- 各チャットルームの最新コメント
60
60
  select
61
- s.*,
61
+ c.*,
62
62
  -- 適宜エイリアス付けてください。省略してるので
63
63
  latest_comments.body,
64
64
  latest_comments.created_at
@@ -66,7 +66,7 @@
66
66
  chatspace c
67
67
  join
68
68
  latest_comments
69
- on latest_comments.chatspace_id = latest_comments.chatspace_id
69
+ on latest_comments.chatspace_id = c.chatspace_id
70
70
  ```
71
71
 
72
72
  MySQL5系ならWithのところをサブクエリでchatspace へjoinする形になります。

1

低評価された方、理由のコメントを。

2022/09/24 19:27

投稿

m.ts10806
m.ts10806

スコア80850

test CHANGED
@@ -1 +1,78 @@
1
1
  order by でcreated_at降順にしてlimit 1
2
+
3
+ したのをJOIN
4
+
5
+ ※[構文チェッカー](https://rakko.tools/tools/36/)済みですが、実テーブルでの検証まではしていません。
6
+
7
+ 例えば。
8
+ ```SQL
9
+ select
10
+ s.*
11
+ -- 適宜エイリアス付けてください。省略してるので
12
+ cc.body,
13
+ cc.created_at
14
+ from
15
+ chatspace c
16
+ JOIN
17
+ (
18
+ SELECT
19
+ chatspace_id,
20
+ body,
21
+ created_at
22
+ FROM
23
+ comments m
24
+ where
25
+ chatspace_id = c.chatspace_id
26
+ order by
27
+ created_at
28
+ limit 1
29
+ ) cc
30
+ ```
31
+
32
+ MAXを活かすならこんな感じにも組めると思う。(もしかしたらこちらのほうが想定通りにとれるかもしれない)
33
+ MySQL8ならこんな感じ。
34
+ ```SQL
35
+ -- 最新コメントIDリスト
36
+ with latest_comments_id_list as(
37
+ SELECT
38
+ chatspace_id,
39
+ MAX(created_at) as latest_comments_created_at
40
+ FROM
41
+ comments
42
+ GROUP BY
43
+ chatspace_id
44
+ ),
45
+ -- 各IDごとの最新コメント
46
+ latest_comments as(
47
+ SELECT
48
+ latest_comments_id_list.chatspace_id,
49
+ c.body,
50
+ latest_comments_created_at
51
+ from
52
+ comments c
53
+ join
54
+ latest_comments_id_list
55
+ on latest_comments_id_list.chatspace_id = c.chatspace_id
56
+ and latest_comments_created_at = c.created_at
57
+ )
58
+
59
+ -- 各チャットルームの最新コメント
60
+ select
61
+ s.*,
62
+ -- 適宜エイリアス付けてください。省略してるので
63
+ latest_comments.body,
64
+ latest_comments.created_at
65
+ from
66
+ chatspace c
67
+ join
68
+ latest_comments
69
+ on latest_comments.chatspace_id = latest_comments.chatspace_id
70
+ ```
71
+
72
+ MySQL5系ならWithのところをサブクエリでchatspace へjoinする形になります。
73
+
74
+ 場合によってはSELECT句にサブクエリ付けてもいいかもしれませんが、
75
+ SQL1本でやらずに、
76
+ ①チャットルームの一覧を取得してループ
77
+ ②ループ内で最新コメント取得(ここはorder by + limit1のほうがいい)
78
+ と分けてやっても良いと思います。