获取朋友的个人资料帖子

时间:2013-08-18 20:56:33

标签: php mysql

我正在制作一个小型CMS,在那里你可以有朋友,并在他们的墙上张贴。我正在创建一个页面,您可以在其中查看您朋友发布的所有帖子(在他们的个人资料中),但是,我无法正常运行。

表:朋友

+---------------+---------+------+-----+---------+----------------+
| Field         | Type    | Null | Key | Default | Extra          |
+---------------+---------+------+-----+---------+----------------+
| friend_id     | int(10) | NO   | PRI | NULL    | auto_increment |
| user1_id      | int(10) | NO   |     | NULL    |                |
| user2_id      | int(10) | NO   |     | NULL    |                |
| friends_since | int(10) | NO   |     | NULL    |                |
+---------------+---------+------+-----+---------+----------------+

表:profile_posts

+----------------+---------+------+-----+---------+----------------+
| Field          | Type    | Null | Key | Default | Extra          |
+----------------+---------+------+-----+---------+----------------+
| post_id        | int(12) | NO   | PRI | NULL    | auto_increment |
| posted_user_id | int(12) | YES  |     | NULL    |                |
| user_id        | int(12) | YES  |     | NULL    |                |
| date_posted    | int(11) | YES  |     | NULL    |                |
| total_likes    | int(12) | YES  |     | NULL    |                |
| users_liked    | text    | YES  |     | NULL    |                |
| total_dislikes | int(12) | YES  |     | NULL    |                |
| users_dislikes | text    | YES  |     | NULL    |                |
| message        | text    | YES  |     | NULL    |                |
+----------------+---------+------+-----+---------+----------------+

基本上,如果我想确定用户是否在其个人资料上发布了状态,则表profile_posts中的posting_user_id和user_id列必须匹配(posting_user_id是用户发布的帖子的ID,而user_id是user_id是发布该消息的人的ID。

但是,我已多次尝试获取朋友的状态。

SELECT *
FROM `friends` AS `f`
LEFT JOIN `profile_posts` AS `pp`
    ON `pp`.posted_user_id = `pp`.user_id
WHERE 
    `f`.user1_id != 2 OR
    `f`.user2_id != 2
ORDER BY `pp`.`date_posted` DESC
LIMIT 0,15;

(Hurray不工作!:D)

SELECT `f`.*,`pp`.*,
    IF(`f`.user1_id=2, `f`.user2_id, `f`.user1_id) AS `uid`
FROM `friends` AS `f`
LEFT JOIN `profile_posts` AS `pp`
    ON `pp`.posted_user_id =`uid`
WHERE 
    `f`.user1_id = `uid` OR
    `f`.user2_id = `uid`
ORDER BY `pp`.`date_posted` DESC
LIMIT 0,15;

我不确定如何诚实地做到这一点,它开始让我愤怒,因为我无法想象如何做到这一点。 :/

1 个答案:

答案 0 :(得分:1)

没关系,想出怎么做。 :d

修改

SELECT 
    `f`.*,
    `pp`.*,
    `ai`.`name`,
    `ai`.`lastname`
FROM `friends` AS `f`
LEFT JOIN `profile_posts` AS `pp`
    ON
        `pp`.`posted_user_id` = `pp`.`user_id` AND
        `pp`.`user_id` = `f`.user1_id OR
        `pp`.`user_id` = `f`.user2_id
LEFT JOIN `account_info` AS `ai`
    ON `ai`.`u_id` = `pp`.`user_id`
WHERE
    `pp`.`user_id` = `pp`.`posted_user_id` AND
    `f`.user1_id = 1 OR
    `f`.user2_id = 1 AND
    `pp`.`user_id` = `pp`.`posted_user_id`
GROUP BY `pp`.post_id
ORDER BY `pp`.date_posted DESC
LIMIT 0,20;

选择当前用户的朋友,然后抓取他们朋友的所有个人资料帖子,然后加入帐户信息表以获取姓名和其他信息。

我试图看看我是否可以让它更小,如果不是更好......