如何从两个不同的表中为多个用户获取数据?

时间:2019-07-14 12:03:49

标签: php mysql

我为用户提供1个表,为注释提供1个表,下面为朋友提供1个表:

评论表:

------------------------------------------------
| comment_id  | user_id_c | commentstatus      | 
------------------------------------------------
|  1          |   1       |   Sample comment 1 |
|  2          |   2       |   Sample comment 2 |
------------------------------------------------

用户表:

------------------------------------------------------
| id  | username            | password  |  Full name |
------------------------------------------------------
|  1  |   user1 (loggedin)  | Sample 1  |  John      |
|  2  |   user2             | Sample 2  |  Smith     |
|  3  |   user3             | Sample 3  |  Andrew    |
|  4  |   user4             | Sample 4  |  Victor    |
|  3  |   user5             | Sample 3  |  Robert    |  
-------------------------------------------------------

朋友桌

---------------------------------------------------
| id  | friend1             | friend2   |   status   
---------------------------------------------------
|  1  |   user1             | user3     |  friend
|  2  |   user1             | user5     |  friend
|  3  |   user2             | user4     |  friend
---------------------------------------------------

当前,如果有任何用户发布评论,它将被插入评论表中的数据库中。现在,如果我已登录,则可以从数据库中获取所有评论。

为了说明这一点,我想通知大家,根据friends表,用户1是用户3和用户5的朋友。

我只想获取已登录用户以及与已登录用户为好友的评论。但是,我无法弄清楚如何获取已登录用户及其朋友的评论。

我用来提取帖子的脚本如下:

public function comments(){
            global $pdo;
            $query = $pdo->prepare("SELECT u.*, c.* FROM users u INNER JOIN comments c ON u.id = c.user_id_c WHERE u.id = ".$_SESSION['sid']." ORDER BY c.comment_id DESC");
            $query->execute();
            return $query->fetchAll();
        }

,然后使用以下代码获取评论:

$comments  = $get->comments();

然后:

foreach($comments as $row){

echo $row['Full name']; //user name from user table in the database
echo $row['commentstatus']; //comment from comments table in the database

它正在为登录用户完美地获取数据,无论如何,我是否还能同时从数据库中登录用户的评论中获取登录用户朋友的评论。

1 个答案:

答案 0 :(得分:0)

您正在寻找这样的东西:

$query = $pdo->prepare("SELECT u.*, c.* FROM users u INNER JOIN comments c ON u.id = c.user_id_c WHERE u.id = ".$_SESSION['sid']." OR c.user_id IN (SELECT friend_id FROM friends WHERE friends.user_id = ".$_SESSION['sid'].") ORDER BY c.comments_id DESC"