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

4

1 回答 1

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.

于 2013-04-28T22:24:17.010 回答