2013-04-15 68 views
4

後目前我有此查詢:MySQL的限制LEFT JOIN子查詢加盟

SELECT post.id AS postID, sCom.id as CommentID FROM `post` LEFT JOIN (SELECT * FROM `comment` LIMIT 5) AS sCom ON sCom.post_id = post.id; 

輸出:

postID | CommentID 
1  | 1 
2  | null 
3  | null 
4  | 2 
5  | 3 
5  | 4 
5  | 5 

它的工作原理,但它在加入之前,限制了意見表。結果是,它選擇前5個評論並映射它。對5個ID的所有評論都會被忽略。

如何重寫查詢以獲得最多5條評論選中的帖子?

當前的表結構:

帖子:

 
CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`feed_id` int(11) DEFAULT NULL, 
`user_id` int(11) DEFAULT NULL, 
`origin_id` int(11) DEFAULT NULL, 
`content` longtext COLLATE utf8_unicode_ci NOT NULL, 
`enabled` tinyint(1) NOT NULL, 
`created_at` datetime NOT NULL, 
`updated_at` datetime NOT NULL, 
PRIMARY KEY (`id`), 
KEY `IDX_5A8A6C8D51A5BC03` (`feed_id`), 
KEY `IDX_5A8A6C8DA76ED395` (`user_id`), 
KEY `IDX_5A8A6C8D56A273CC` (`origin_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ; 

評論:

 
CREATE TABLE IF NOT EXISTS `comment` (
`id` int(11) NOT NULL AUTO_INCREMENT, 
`feed_id` int(11) DEFAULT NULL, 
`user_id` int(11) DEFAULT NULL, 
`post_id` int(11) DEFAULT NULL, 
`content` longtext COLLATE utf8_unicode_ci NOT NULL, 
`enabled` tinyint(1) NOT NULL, 
`created_at` datetime NOT NULL, 
`updated_at` datetime NOT NULL, 
PRIMARY KEY (`id`), 
KEY `IDX_9474526C51A5BC03` (`feed_id`), 
KEY `IDX_9474526CA76ED395` (`user_id`), 
KEY `IDX_9474526C4B89032C` (`post_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=11 ; 

感謝

回答

6

這會給你的每一個崗位5個評論。

SELECT p.*, 
     c.* 
FROM Post p 
     LEFT JOIN 
     (
      SELECT a.* 
      FROM Comments a 
      WHERE  
        (
         SELECT COUNT(*) 
         FROM  Comments b 
         WHERE a.Post_ID = b.Post_ID AND 
           a.ID <= b.ID 
        ) <= 5 
     ) c ON a.ID = c.Post_ID 
+0

完美地工作。謝謝 – geNAZt

+0

不客氣':D' –

+1

@JohnWoo謝謝,這對我有幫助,但我認爲''a.ID = c.Post_ID'必須是'p.ID = c.Post_ID' – xurshid29