I am basically trying to join user info with my messages table. I basically want to get all messages from a given user that have been sent to them or they have sent out. My messages table looks like this:
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;
Users table looks like this:
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 ;
I've tried the following queries:
$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";
The problem is that these return the wrong from
user. I would like to know who the message was sent to if the logged user composed the message and vice versa who the message was if it was sent to the given user.
Is this possible to do in one query or do I have to have a separate query for sent and received messages?