我想知道如何创建SQL查询以仅从我关注的人那里获取消息。我假设创建SQL连接查询是正确的方法,但我不知道如何。请有人帮帮我吗?
我现在有这三张桌子:
CREATE TABLE `users` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`email` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 8 ) NOT NULL ,
`status` ENUM( 'active', 'inactive' ) NOT NULL
) ENGINE = MYISAM ;
CREATE TABLE `posts` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`user_id` INT NOT NULL ,
`body` VARCHAR( 140 ) NOT NULL ,
`stamp` DATETIME NOT NULL
) ENGINE = MYISAM ;
CREATE TABLE `following` (
`user_id` INT NOT NULL ,
`follower_id` INT NOT NULL ,
PRIMARY KEY ( `user_id` , `follower_id` )
) ENGINE = MYISAM ;
非常感谢您的回复。
答案 0 :(得分:2)
试试这个:
select p.body, p.stamp, pu.username
from posts p
join
following f
on f.user_id = p.user_id
join
users you
on you.user_id = f.follower_id
join
users pu
on pu.user_id = p.user_id
where you.username = 'obadja7'
;
......或类似的东西。
罗布
答案 1 :(得分:2)
现在你有3个答案:JOIN,IN,EXISTS
SELECT *
FROM POSTS p
WHERE EXISTS (SELECT *
FROM following f
WHERE f.follower_id = @your_id AND f.user_id = p.user_id)
我通常会使用EXISTS:
答案 2 :(得分:1)
像这样:
SELECT * FROM POSTS
WHERE user_id IN (SELECT user_id FROM following
WHERE follower_id = @your_id)