Question

SELECT M.msg_id, M.uid_fk, M.message, M.created, 
U.fname, U.lname, M.uploads 
FROM messages M, users_friends F, users U  
WHERE M.uid_fk=F.friendID 
and F.userID = '5'
and status='2'

Building a facebook-like wall and want to grab messages(updates) from friends.

The query above returns an empty set, even though I've made sure there are messages from user 5 in the table.

Schema:

CREATE TABLE IF NOT EXISTS `messages` (
  `msg_id` int(11) NOT NULL AUTO_INCREMENT,
  `message` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
  `uid_fk` int(11) DEFAULT NULL,
  `ip` varchar(30) DEFAULT NULL,
  `created` int(11) DEFAULT '1269249260',
  `uploads` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`msg_id`),
  KEY `uid_fk` (`uid_fk`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=263 ;


CREATE TABLE IF NOT EXISTS `users` (
  `fname` varchar(15) NOT NULL,
  `lname` varchar(15) NOT NULL,
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(23) NOT NULL,
  `email` varchar(50) NOT NULL,
  `password` varchar(32) NOT NULL,
  `DOB` date DEFAULT NULL,
  `sex` varchar(1) DEFAULT NULL,
  `about` text NOT NULL,
  `location` varchar(20) DEFAULT NULL,
  `last_login` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `user_level` int(11) NOT NULL DEFAULT '0',
  `profile_image` varchar(200) NOT NULL,
  `profile_image_small` varchar(200) NOT NULL,
  PRIMARY KEY (`userID`)
 ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ;


CREATE TABLE IF NOT EXISTS `users_friends` (
  `userID` int(11) NOT NULL,
  `friendID` int(11) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`userID`,`friendID`),
  KEY `fk_users_has_friends_users1` (`userID`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Was it helpful?

Solution

You are single quoting your INT values in the WHERE clause → '5' & '2'.

Also, try JOINs.

SELECT  M.msg_id, 
        M.uid_fk, 
        M.message, 
        M.created, 
        U.fname, 
        U.lname, 
        M.uploads 
FROM    messages M
INNER JOIN  users_friends F ON F.friendID = M.uid_fk
    AND F.userID = 5
    AND F.status = 2
INNER JOIN  users U ON U.userID = F.friendID;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top