sql无法弄清楚查询

时间:2014-12-17 20:00:02

标签: mysql sql

我有三张桌子:

CREATE TABLE IF NOT EXISTS `contacts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `providerId` int(10) unsigned NOT NULL DEFAULT '0',
  `requestId` int(10) unsigned NOT NULL DEFAULT '0',
  `status` binary(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
)

CREATE TABLE IF NOT EXISTS `messages` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `fromuid` int(255) NOT NULL,
  `touid` int(255) NOT NULL,
  `sentdt` datetime NOT NULL,
  `read` tinyint(1) NOT NULL DEFAULT '0',
  `readdt` datetime DEFAULT NULL,
  `messagetext` longtext CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  PRIMARY KEY (`id`),
  KEY `id` (`id`)
)

CREATE TABLE IF NOT EXISTS `users` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `mobile` varchar(15) NOT NULL,
  `password` varchar(255) NOT NULL,
  `city` varchar(255) NOT NULL,
  `zip` varchar(15) DEFAULT NULL,
  `device` varchar(50) DEFAULT NULL,
  `version` varchar(10) DEFAULT NULL,
  `photo` varchar(255) DEFAULT NULL,
  `created` datetime NOT NULL,
  `live` enum('0','1') NOT NULL DEFAULT '1',
  `authenticationTime` datetime NOT NULL,
  `userKey` varchar(255) DEFAULT NULL,
  `IP` varchar(50) DEFAULT NULL,
  `port` int(10) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `firstname` (`mobile`,`city`,`zip`)
)

此SQL查询找出指定用户的朋友/联系人(在这种情况下为用户ID 1):

SELECT u.id
   ,u.mobile
   ,u.name
   ,(NOW() - u.authenticationTime) AS authenticateTimeDifference
   ,u.IP
   ,f.providerid
   ,f.requestid
   ,f.status
   ,u.port
FROM contacts f
LEFT JOIN users u ON u.id =
IF (
      f.providerid = 1
      ,f.requestid
      ,f.providerid
      ) WHERE (
      f.providerid = 1
      AND f.status = 1
      )
   OR f.requestid = 1

工作正常,但我希望能够加入消息表和显示用户的朋友/联系人,他们已经使用order by messages.sentdt desc选项进行了最新的谈话(意思是最新的会话),但我是无法弄清楚如何做到这一点,我尝试了所有的连接但没有工作:(

非常感谢您的帮助。感谢

更新

以上是查询返回的示例数据:

enter image description here

相同的结果集中,我希望能够基于order by messages.sentdt desc进行排序,但我不知道如何将其拉入并按最新消息排序结果集

1 个答案:

答案 0 :(得分:0)

试试这个:     

  select u.id
      , u.mobile
      , u.name
      , (NOW() - u.authenticationTime) as authenticateTimeDifference
      , u.IP
      , f.providerid
      , f.requestid
      , f.status
      , u.port
    from contacts f
    left join users u
      on u.id = if (f.providerid = 1, f.requestid, f.providerid)
    left join (select fromuid, max(sentdt) as sentdt from messages group by fromuid) m 
      on m.fromuid =  if (f.providerid = 1, f.providerid, f.requestid)
    where (f.providerid = 1 and f.status = 1) 
        or f.requestid = 1
    order by m.sentdt