0
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'

建立一个类似 facebook 的墙,并希望从朋友那里获取消息(更新)。

上面的查询返回一个空集,即使我已经确定表中有来自用户 5 的消息。

架构:

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;
4

1 回答 1

1

您在 WHERE 子句→“5”和“2”中单引号引用您的 INT 值。

另外,尝试 JOIN。

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;
于 2012-02-20T00:52:37.900 回答