使用消息表加入用户信息

时间:2014-01-29 01:56:39

标签: mysql sql join create-table

我基本上是尝试将用户信息加入我的消息表。我基本上想要获取已发送给他们或已发送的给定用户的所有消息。我的消息表看起来像这样:

CREATE TABLE IF NOT EXISTS `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `toId` int(11) NOT NULL,
  `fromId` int(11) NOT NULL,
  `msg` text NOT NULL,
  `createdOn` varchar(100) NOT NULL,
  `status` enum('new','unread','read','archived','deleted') NOT NULL DEFAULT 'new',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=31;

用户表如下所示:

CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `pid` int(11) NOT NULL,
  `gender` enum('male','female') NOT NULL,
  `fname` varchar(25) NOT NULL,
  `lname` varchar(25) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(25) NOT NULL,
  `state` varchar(2) NOT NULL,
  `zip` int(5) NOT NULL,
  `email` varchar(100) NOT NULL,
  `username` varchar(50) NOT NULL,
  `about` text NOT NULL,
  `createdOn` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=61 ;

我尝试了以下查询:

$messages = "SELECT * FROM ( SELECT messages.*, users.pid, users.username FROM messages, users WHERE messages.fromId = users.id AND messages.toId = '". $_COOKIE['id'] ."' ORDER BY messages.createdOn DESC ) as messages GROUP BY fromId";

$messages = "SELECT messages.toId, messages.fromId, messages.msg, messages.createdOn, users.pid, users.username FROM messages, users WHERE ( messages.toId = ". $_COOKIE['id'] ." OR messages.fromId = ". $_COOKIE['id'] ." ) AND messages.fromId = users.id GROUP BY messages.fromId ORDER BY messages.createdOn DESC";

$messages = "SELECT messages.* FROM messages JOIN ( SELECT messages.fromId, max(messages.createdOn) as date_creation FROM messages WHERE messages.toId = 1 GROUP BY messages.fromId ) users ON messages.fromId = users.id";

问题是这些用户返回了错误的from用户。我想知道如果已记录的用户组成了消息,则将消息发送给谁,反之亦然,如果消息是发送给给定用户的话,该消息是谁。

这可以在一个查询中执行,还是必须对发送和接收的消息进行单独查询?

1 个答案:

答案 0 :(得分:1)

我认为您可以谨慎使用case语句来获得您想要的内容:

select id, (case when $_COOKIE['id'] = fromid then toId else FromId end) as OtherId,
       (case when $_COOKIE['id'] = fromid then 'sent' else 'received' end) as which,
       msg, createdOn, status
from messages m
where $_COOKIE['id'] in (fromId, toId) ;