2015-10-19 56 views
-1

我有,人们可以发送意见表:评论答案MySQL的

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 id, user, data, ip, answer from comments where reference = ? and answer = 0 

,所以我可以通过参考ID得到所有发表评论,并跳过它,如果它是一个答案。

问题是,如果有一条评论有答案,我该如何在其选择的评论中选择这个答案?例如:

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 
... 

回答

0

我想你可以

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中,你可以遍历结果,并组建一个阵列accoding您的需求。

+1

谢谢你的朋友!我会试试这个! –