2013-03-13 84 views
1

我有兩個表一個是「forum_topic」和第二個是「forum_comments」PHP MySQL查詢在笨

我希望有一個笨查詢得到forum_topic細節,比如我有一個查詢從forum_topic其中「SELECT * topic_id = 1「然後我想從forum_comments表基於」forum_comments.topic_id = forum_topic.topic_id「的所有評論,但論壇評論應該是樹形視圖格式,因爲我們也有每個評論的n級回覆也存儲在「forum_comments」表中,您可以在forum_comments表中看到有一個字段「parent」,其中包含「comment_id」,對其進行回覆。

1 - forum_topic

CREATE TABLE IF NOT EXISTS `forum_topic` (
    `topic_id` int(11) NOT NULL AUTO_INCREMENT, 
    `title` varchar(255) NOT NULL, 
    `category` int(11) NOT NULL, 
    `content` text NOT NULL, 
    `created_by` int(11) NOT NULL, 
    `created_date` datetime NOT NULL, 
    `view_count` int(11) NOT NULL, 
    `last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
    `status` enum('publish','unpublish') NOT NULL, 
    PRIMARY KEY (`topic_id`) 
) 

2 - forum_comments

CREATE TABLE IF NOT EXISTS `forum_comments` (
    `comment_id` int(11) NOT NULL AUTO_INCREMENT, 
    `comment_by` int(11) NOT NULL, 
    `topic_id` int(11) NOT NULL, 
    `parent` int(11) NOT NULL DEFAULT '0', 
    `comment` text NOT NULL, 
    `commented_date` datetime NOT NULL, 
    `commented_type` enum('user','admin') NOT NULL DEFAULT 'user', 
    `status` enum('publish','unpublish','block') NOT NULL, 
    PRIMARY KEY (`comment_id`) 

+3

你有什麼試過..? – Gautam3164 2013-03-13 06:40:38

+0

我用自定義代碼嘗試過,激發多個查詢 – 2013-03-13 06:43:33

+0

所以你只需要基於論壇主題的主題標識進行評論? – 2013-03-13 06:44:40

回答

0

如果您在大量的循環尋找效率或加入,我會對'forum_comments'表使用「左右樹」格式:

http://www.sitepoint.com/hierarchical-data-database-2/

http://en.wikipedia.org/wiki/Nested_set_model

+0

我只想要一個幫助,如何根據樹形格式的主題ID獲得評論,我可以使用兩個查詢一個是forum_topic,第二個是所有評論 – 2013-03-13 06:51:13

+0

簡單,將列(左,右,深度)添加到您的forum_comments ,然後只需SELECT * FROM forum_comments WHERE topic_id = $ topic_id ORDER BY left ASC。那是你的樹。如果你不想做這些讀物,那麼我就沒有辦法提供幫助。第一篇文章告訴你如何做更新/刪除項目,並通過一些練習(不包括在文章中),你甚至可以根據左側和右側移動子樹。深度不是必需的,但可以讓您的佈局更輕鬆。 – 2013-03-13 07:32:17

+0

謝謝,我會嘗試 – 2013-03-13 07:45:24

0

可以使用模型函數像這樣與查詢

function getComments($topic_id){ 
    $query = " SELECT 
         fc.* 
        FROM forum_topic AS ft 
        INNER JOIN forum_comments AS fc ON ft.topic_id = fc.topic_id 
        WHERE ft.topic_id = $topic_id 
        ORDER BY fc.parent"; 
    return $this->db->query($query)->result(); 
} 
+0

感謝raheel,我認爲這可以幫助我。我正在嘗試使用您的解決方案。 – 2013-03-13 07:17:52

+0

我的評論表 – 2013-03-13 07:23:29

+0

謝謝死人,我正在應用你們發送的可能解決方案 – 2013-03-13 07:29:17

0

你可以試試這個查詢,看看它的工作原理:

Select top.*,com.* from forum_topic as top left join forum_comments as com on com.topic_id = top.topic_id where top.topic_id = 1 order by top.topic_id desc