2013-04-28 59 views
0

我工作的兩個表,訂單查詢結果由最新更新日期

CREATE TABLE IF NOT EXISTS `users` (
    `userid` INT NOT NULL AUTO_INCREMENT , 
    `fname` VARCHAR(45) NOT NULL , 
    `lname` VARCHAR(45) NOT NULL , 
    `usernick` VARCHAR(45) NOT NULL , 
    PRIMARY KEY (`userid`) , 
    UNIQUE INDEX `usernick_UNIQUE` (`usernick` ASC)) 
ENGINE = InnoDB; 

CREATE TABLE IF NOT EXISTS `messages` (
    `messageid` INT NOT NULL AUTO_INCREMENT , 
    `sendid` INT NOT NULL , 
    `recid` INT NOT NULL , 
    `message` VARCHAR(1000) NOT NULL , 
    `date` TIMESTAMP NULL , 
    PRIMARY KEY (`messageid`) , 
    INDEX `sender_fk_idx` (`sendid` ASC) , 
    INDEX `reciever_fk_idx` (`recid` ASC) , 
    CONSTRAINT `sender_fk` 
    FOREIGN KEY (`sendid`) 
    REFERENCES `users` (`userid`) 
    ON DELETE CASCADE 
    ON UPDATE CASCADE, 
    CONSTRAINT `reciever_fk` 
    FOREIGN KEY (`recid`) 
    REFERENCES `users` (`userid`) 
    ON DELETE CASCADE 
    ON UPDATE CASCADE) 
ENGINE = InnoDB; 

和希望的用戶列表的基礎上,如果他們最後發送的消息。例如。

select U.fname,U.lname,U.usernick from messages as M natural join users as U where M.sendid = U.userid and M.recid={$_SESSION['user_id']} group by U.usernick ORDER BY M.date DESC 

例:

name   msg sent to "RON" on 

Alpha  17 aug 
Beta   18 aug 
Alpha  19 aug 
Gamma  20 aug 


SO i want a list like, 

gamma (last msg on 20) 
alpha (last msg on 18) 
beta (last msg on 19) 

見鏈接http://sqlfiddle.com/#!2/9dca2/2/0

回答

0

你幾乎有它。您只需在order by條款中使用max(m.date)。否則,選擇任意日期:

select U.fname,U.lname,U.usernick 
from messages as M join 
    users as U 
     on M.sendid = U.userid 
where M.recid={$_SESSION['user_id']} 
group by U.usernick 
ORDER BY max(M.date) DESC 

我還修復了join語法。最好避免自然連接 - 也就是說,要明確連接條件。你這樣做反正,所以我切換條件的on子句和natural joinjoin

+0

謝謝!解決了! – unkn0wn 2013-04-28 22:27:11