USER_TABLE
user_id | username
1 | solomon
2 | muna
消息表
id user_id| message
1 1 | this is my first message
2 1 | this is my seocnd message
3 2 | this is muna messgae
关系表
leader | follower
1 | 2
|
我想要做的是一个三桌加入来带出muna的朋友信息,目前muna跟随所罗门(如关注者表所示),
所以我希望在mona主页上显示如下:
Solomon "this is my my first message
----------------------------------
solomon "this is my second message"
P.S。这只是一个示例数据库,我只是想看看如何处理这个问题,这就是我到目前为止的尝试!
select username, message, leader
from user, message, relationship where user.user_id =notes.user_id
and user.user_id = relationship.leader and where user_id = $_SESSION['user_id']
*会话ID是muna,即user_id 2
答案 0 :(得分:5)
这是一种做法的方式
SELECT m.message,u.username FROM relationships r, messages m,users u WHERE m.user_id = r.leader AND r.leader = u.user_id AND u.user_id = 1
间隔
SELECT
m.message,u.username #here you can use m.* to retrieve all data
FROM
relationships r, #Here you can define what tables you want to use
messages m, #within your query, always remember to do table_name letter
users u #this will stop ambiguity within the queries
WHERE
m.user_id = r.leader #make sure the message user id is the same as the leader id
AND
r.leader = u.user_id #same as above just making the messages be filtered to the user_id
AND
u.user_id = 1 #your overall id will be here, if this was 2 it would affect WHERE, and AND above.
在应用程序中
$query = mysql_query('SELECT m.message,u.username FROM relationships r, messages m,users u WHERE m.user_id = r.leader AND r.leader = u.user_id AND u.user_id = ' . intval($_SESSION['user_id']));
while($row = mysql_fetch_assoc($query))
{
echo sprintf("%s: %s",$row['username'],$row['message']);
echo "\r\n--------------------------------------------";
}
这已经过测试,可以在下表结构中正常工作。
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`message` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
INSERT INTO `messages` (`id`, `user_id`, `message`) VALUES
(1, 1, 'test'),
(2, 1, 'test 2'),
(3, 2, 'test 3');
CREATE TABLE IF NOT EXISTS `relationships` (
`leader` int(11) NOT NULL,
`follower` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `relationships` (`leader`, `follower`) VALUES
(1, 2);
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `users` (`user_id`, `username`) VALUES
(1, 'solomon'),
(2, 'muna');
答案 1 :(得分:4)
我不确定你的问题是什么。这看起来像是答案吗?
SELECT u.username,
m.message
FROM user u
JOIN message m
ON u.user_id =m.user_id
JOIN relationship r
ON u.user_id = r.leader
WHERE u.user_id = $_SESSION['user_id']