2012-04-26 36 views
0

我需要提取的每個配置文件的最後一個評論,在過去的100個型材如何提取每個配置文件的最後評論?

每個配置文件,如果類型== 1,具有至少1條評論

  • 類型== 1 =>是公司
  • 類型== 2 =>是人

下面是相關的表和數據:

CREATE TABLE IF NOT EXISTS `comment` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `profile` int(11) NOT NULL, 
    `name` varchar(200) NOT NULL, 
    `email` varchar(200) NOT NULL, 
    `county` int(11) NOT NULL, 
    `comment` text NOT NULL, 
    `created` int(11) NOT NULL, 
    `status` int(11) NOT NULL, 
    `verified` int(11) NOT NULL, 
    UNIQUE KEY `id` (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; 

INSERT INTO `comment` (`id`, `profile`, `name`, `email`, `county`, `comment`, `created`, `status`, `verified`) VALUES 
(1, 1, 'ANGAJAT 1', 'email 2', 1, 'comm 1', 1335423985, 0, 0), 
(2, 3, 'ANGAJAT 2', 'email 4', 1, 'comm 2', 1335424011, 0, 0), 
(3, 5, 'ANGAJAT 3', 'email 6', 1, 'comm 3', 1335424037, 0, 0), 
(4, 5, 'ANGAJAT 3', 'email 6', 1, 'comm 4', 1335424039, 0, 0); 

CREATE TABLE IF NOT EXISTS `profile` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `type` int(11) NOT NULL COMMENT '1 = angajatori ; 2 - angajati', 
    `name` varchar(200) NOT NULL, 
    `county` int(11) NOT NULL, 
    `email` varchar(200) NOT NULL, 
    `created` int(11) NOT NULL, 
    `comments` int(11) NOT NULL, 
    `status` int(11) NOT NULL, 
    `verified` int(11) NOT NULL, 
    UNIQUE KEY `id` (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; 

INSERT INTO `profile` (`id`, `type`, `name`, `county`, `email`, `created`, `comments`, `status`, `verified`) VALUES 
(1, 1, 'ANGAJATOR 1', 1, 'email 1', 1335423985, 0, 0, 0), 
(2, 2, 'ANGAJAT 1', 1, 'email 2', 1335423985, 0, 0, 0), 
(3, 1, 'ANGAJATOR 2', 1, 'email 3', 1335424011, 0, 0, 0), 
(4, 2, 'ANGAJAT 2', 1, 'email 4', 1335424011, 0, 0, 0), 
(5, 1, 'ANGAJATOR 3', 1, 'email 5', 1335424037, 0, 0, 0), 
(6, 2, 'ANGAJAT 3', 1, 'email 6', 1335424037, 0, 0, 0);\ 

我想:

SELECT * 
FROM COMMENT c 
JOIN profile p ON p.id = c.profile 
GROUP BY c.profile 
ORDER BY c.created DESC , p.id ASC 
LIMIT 100 

和我:

id profile name email county comment created status verified id type name county email created comments status verified 
3 5 ANGAJAT 3 email 6 1 comm 3 1335424037 0 0 5 1 ANGAJATOR 3 1 email 5 1335424037 0 0 0 
2 3 ANGAJAT 2 email 4 1 comm 2 1335424011 0 0 3 1 ANGAJATOR 2 1 email 3 1335424011 0 0 0 
1 1 ANGAJAT 1 email 2 1 comm 1 1335423985 0 0 1 1 ANGAJATOR 1 1 email 1 1335423985 0 0 0 

查詢返回的每100最後公司

請與查詢幫助

+0

身份證從配置文件,是一個FK的評論,被稱爲配置文件 – 2012-04-26 08:19:09

回答

1

試試這個第一個評論:

SELECT c.* 
FROM COMMENT c 
JOIN 
    (SELECT MAX(created_at) created_at, profile FROM COMMENT 
    GROUP BY profile) p ON p.profile = c.profile AND p.created_at = c.created_at 
ORDER BY c.created DESC , p.profile ASC 
LIMIT 100 

它應該做的伎倆。

+0

不,更糟糕:D – 2012-04-26 11:58:52

+0

好吧,修復,我希望。請嘗試一下。 – Matzi 2012-04-26 12:36:18

+0

我會在晚些時候嘗試它 – 2012-04-30 13:15:44