评论回答mysql
Comment answer mysql
我有一个 table 人们可以发送评论:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` int(11) UNSIGNED NOT NULL,
`reference` int(11),
`data` datetime NOT NULL,
`ip` varchar(20),
`answer` int(11)
PRIMARY KEY (`id`)
)
如果此评论是对另一条评论的回答 answer
有其 ID。
我有这个 select:
select id, user, data, ip, answer from comments where reference = ? and answer = 0
所以我可以通过引用 ID 获取所有 post 评论,如果是答案则跳过它。
问题是,如果一个评论有答案,我怎么能select在这个select的评论里面回答呢?例如:
comment 1
answer comment 1 (1)
answer comment 1 (2)
comment 2
comment 3
comment 4
answer comment 4 (1)
answer comment 4 (2)
comment 5
...
我想你可以
SELECT q.id as question_id , q.user as question_user,
q.data as question_data, q.ip as question_ip,
a.id as answer_id , q.user as answer_user,
a.data as answer_data, a.ip as answer_ip
FROM comments q LEFT JOIN comments a on q.id=a.answer
WHERE q.reference = ?
然后在 php 中你可以遍历结果和 assemble 一个满足你需要的数组。
我有一个 table 人们可以发送评论:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` int(11) UNSIGNED NOT NULL,
`reference` int(11),
`data` datetime NOT NULL,
`ip` varchar(20),
`answer` int(11)
PRIMARY KEY (`id`)
)
如果此评论是对另一条评论的回答 answer
有其 ID。
我有这个 select:
select id, user, data, ip, answer from comments where reference = ? and answer = 0
所以我可以通过引用 ID 获取所有 post 评论,如果是答案则跳过它。
问题是,如果一个评论有答案,我怎么能select在这个select的评论里面回答呢?例如:
comment 1
answer comment 1 (1)
answer comment 1 (2)
comment 2
comment 3
comment 4
answer comment 4 (1)
answer comment 4 (2)
comment 5
...
我想你可以
SELECT q.id as question_id , q.user as question_user,
q.data as question_data, q.ip as question_ip,
a.id as answer_id , q.user as answer_user,
a.data as answer_data, a.ip as answer_ip
FROM comments q LEFT JOIN comments a on q.id=a.answer
WHERE q.reference = ?
然后在 php 中你可以遍历结果和 assemble 一个满足你需要的数组。