MySQL Server 5.x を使用しており、サイトの投稿データを格納する posts テーブルがあります。投稿が親投稿の子投稿になる場合があります。この場合、テーブルには投稿の親の ID 番号が記録されます。
このテーブルには、ID フィールド ( bigint )、post_parent フィールド ( bigint も)、タイトル、およびコンテンツがあります。
サンプルデータは次のようになります
ID post_parent title content
----------------------------------------------
1 test testing post content
2 test2 more test content
3 1 test3 post 1 is my parent
4 2 test4 post 2 is my parent
5 tes5 test content post 5
6 2 test6 post 2 is my parent
したがって、X 個のレコードのテーブルをクエリし、その投稿の子を親とグループ化して投稿 ID で結果を並べ替えると、結果は次のようになります。
ID post_parent title content
----------------------------------------------
1 test testing post content
3 1 test3 page 1 is my parent
2 test2 more test content
4 2 test4 page 2 is my parent
6 2 test6 post 2 is my parent
5 test5 test content post 5
したがって、回答に基づいて、明らかに次のようなものを使用できます。
SELECT ID, post_parent, title, content FROM myTable ORDER BY COALESCE(post_parent, ID), ID
しかし、ここでもう 1 つひねりを加える必要があります。テーブルに 16000 個のレコードがランダムな順序であるとします。つまり、2 番目の 100 個のレコード (たとえば、レコード 101 - 200 ) はすべてポストの子である可能性がありますが、子の親が常に返される結果を常に返したいと考えています。子どもたち。したがって、上記のクエリで「limit 100, 25」を使用すると、親を持たない子のみの結果が得られます。どうすればそれを回避し、関連する親が常に子を適切に結合して返すことができますか?