2015-10-19 77 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

謝謝你的朋友!我會試試這個! –