There are many ways. Here is one approach that I like (and is used on a regular basis).
Database
Consider the following database structure:
CREATE TABLE comments (
id int(11) unsigned NOT NULL auto_increment,
parent_id int(11) unsigned default NULL,
parent_path varchar(255) NOT NULL,
comment_text varchar(255) NOT NULL,
date_posted datetime NOT NULL,
PRIMARY KEY (id)
);
Your data will look like this:
+-----+-------------------------------------+--------------------------+---------------+
| id | parent_id | parent_path | comment_text | date_posted |
+-----+-------------------------------------+--------------------------+---------------+
| 1 | null | / | I'm first | 1288464193 |
| 2 | 1 | /1/ | 1st Reply to I'm First | 1288464463 |
| 3 | null | / | Well I'm next | 1288464331 |
| 4 | null | / | Oh yeah, well I'm 3rd | 1288464361 |
| 5 | 3 | /3/ | reply to I'm next | 1288464566 |
| 6 | 2 | /1/2/ | this is a 2nd level reply| 1288464193 |
... and so on...
It’s pretty easy to select everything in the appropriate way:
select id, parent_path, parent_id, comment_text, date_posted
from comments
order by parent_path, date_posted;
parent_path, date_posted , ; , , - , , :
create index comments_hier_idx on comments (parent_path, date_posted);
. where:
select id, parent_path, parent_id, comment_text, date_posted
from comments
where parent_path like '/1/%'
order by parent_path, date_posted;
where , , .
, parent_id. . , , . INNODB:
ALTER TABLE comments ENGINE=InnoDB;
ALTER TABLE comments
ADD FOREIGN KEY ( parent_id ) REFERENCES comments
ON DELETE CASCADE
ON UPDATE CASCADE;
, , , parent_path, . (, , usecase), , .... , .
( db ), - , , , . ( parent_id) parent_path.
parent_path , , , . , .
, - , , , .
MySQL ( ) "" LIMIT:
SELECT * FROM mytable LIMIT 25 OFFSET 0;
, LIMIT .
select id, parent_path, parent_id, comment_text, date_posted
from comments
order by parent_path, date_posted
LIMIT 25 OFFSET 0;
, , "", .
- :
select
a.*
from
comments a join
(select id, parent_path
from comments
where parent_id is null
order by parent_path, post_date DESC
limit 25 offset 0) roots
on a.parent_path like concat(roots.parent_path,roots.id,'/%') or a.id=roots.id)
order by a.parent_path , post_date DESC;
limit 25 offset 0, . 25 "" .
[edit: , , / , . , parent_path. : /{id}/{id2}/{id3}/ post_date _: /{id}:{post_date}/{id2}:{post_date2}/{id3}:{post_date3}/. , .
, .
!