回答編集履歴

6

修正

2017/09/09 07:40

投稿

sazi
sazi

スコア25173

test CHANGED
@@ -4,7 +4,9 @@
4
4
 
5
5
  概要
6
6
 
7
- ・childrenをparent_id毎にcreated_atの昇順(同値のcreated_atを考慮しIDも条件に付加)で連番を振る
7
+ ・childrenをparent_id毎にcreated_atの昇順(同値のcreated_atを考慮しIDも条件に付加)で
8
+
9
+  連番を振る
8
10
 
9
11
  ・連番が指定の番号(30)以下とする。
10
12
 

5

修正

2017/09/09 07:40

投稿

sazi
sazi

スコア25173

test CHANGED
@@ -1,6 +1,14 @@
1
1
  **Ruby on Rails**は触ったことが無いのですが、ここら辺([ActiveRecord ~ 複数テーブルにまたがる検索(先読み、JOINなど)](http://qiita.com/leon-joel/items/f26556c9e56833983856))はご存知な上で、どのようなSQLを書けば良いかが分からないと解釈して、SQLのみの回答です。
2
2
 
3
3
 
4
+
5
+ 概要
6
+
7
+ ・childrenをparent_id毎にcreated_atの昇順(同値のcreated_atを考慮しIDも条件に付加)で連番を振る
8
+
9
+ ・連番が指定の番号(30)以下とする。
10
+
11
+ ・ソートはparents.ID, children.created_at
4
12
 
5
13
  ```SQL
6
14
 
@@ -34,22 +42,4 @@
34
42
 
35
43
  ```
36
44
 
37
- 追記
38
45
 
39
- ---
40
-
41
- 30行毎って要件がありましたね。
42
-
43
- 単に30行に区切って行うには、
44
-
45
- limit [offset,] row_count
46
-
47
- なので
48
-
49
- limit 30*(ページ-1), 30
50
-
51
- とすればよいですが、並び(order by)を指定する必要があります。
52
-
53
- 仮にそれぞれのIDとして、SQLに追記します。
54
-
55
- ページングは、ライブラリに任せた方が良いかと思うのですが、正直その判断はできません。

4

修正

2017/09/09 07:39

投稿

sazi
sazi

スコア25173

test CHANGED
@@ -18,7 +18,9 @@
18
18
 
19
19
  where parent_id=c0.parent_id
20
20
 
21
- and created_at<=c0.created_at
21
+ and created_at<=c0.created_at
22
+
23
+ and id<=c0.id
22
24
 
23
25
  ) as created_order
24
26
 

3

修正

2017/09/08 08:02

投稿

sazi
sazi

スコア25173

test CHANGED
@@ -8,13 +8,27 @@
8
8
 
9
9
  , c.id as cid, c.name as cname
10
10
 
11
- from parents as p left join children as c
11
+ , c.created_at, c.created_order
12
12
 
13
+ from parents as p left join (
14
+
15
+ select *
16
+
17
+ , (select count(*) from children
18
+
13
- on p.id=c.parent_id
19
+ where parent_id=c0.parent_id
20
+
21
+ and created_at<=c0.created_at
22
+
23
+ ) as created_order
24
+
25
+ from children c0
26
+
27
+ ) as c
28
+
29
+ on p.id=c.parent_id and c.created_order<=30
14
30
 
15
31
  order by p.id, c.created_at
16
-
17
- limit 30
18
32
 
19
33
  ```
20
34
 

2

修正

2017/09/08 07:55

投稿

sazi
sazi

スコア25173

test CHANGED
@@ -12,9 +12,9 @@
12
12
 
13
13
  on p.id=c.parent_id
14
14
 
15
- order by p.id, c.id
15
+ order by p.id, c.created_at
16
16
 
17
- limit 30*(ページ-1) , 30
17
+ limit 30
18
18
 
19
19
  ```
20
20
 

1

追記

2017/09/08 05:31

投稿

sazi
sazi

スコア25173

test CHANGED
@@ -12,4 +12,28 @@
12
12
 
13
13
  on p.id=c.parent_id
14
14
 
15
+ order by p.id, c.id
16
+
17
+ limit 30*(ページ-1) , 30
18
+
15
19
  ```
20
+
21
+ 追記
22
+
23
+ ---
24
+
25
+ 30行毎って要件がありましたね。
26
+
27
+ 単に30行に区切って行うには、
28
+
29
+ limit [offset,] row_count
30
+
31
+ なので
32
+
33
+ limit 30*(ページ-1), 30
34
+
35
+ とすればよいですが、並び(order by)を指定する必要があります。
36
+
37
+ 仮にそれぞれのIDとして、SQLに追記します。
38
+
39
+ ページングは、ライブラリに任せた方が良いかと思うのですが、正直その判断はできません。