按最新更新日期订购查询结果

时间:2013-04-28 22:19:42

标签: mysql sql

我正在制作两张桌子,

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

1 个答案:

答案 0 :(得分:0)

你几乎拥有它。您只需要max(m.date)子句中的order by。否则,选择任意日期:

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 join转换为join