如何使用WHERE子句中的一系列值从表中选择多行?

时间:2012-06-12 19:04:32

标签: php mysql

这个问题是如何使用WHERE子句中的一系列值从表中选择多行。这是我想要做的。

我有一个评论应用程序,你发表评论,你的朋友可以回复它,有点像facebook的墙。在同一个应用程序中,我允许每个成员彼此成为朋友。

我现在面临的挑战是,我不仅要展示主人的评论,还要展示他们的朋友。我想要一个类似facebook的墙的功能。
所以这就是我所拥有的:

    Friends Table                           Commenting Table
 _______________________        ___________________________________________
| member_id | friend_id |      | member_id |           comment             |
 -----------------------        -------------------------------------------
|    10     |    14     |      |    10     |      Hello member # 14        |
|    14     |    10     |      |    14     |      hey how are you          |
|    17     |    9      |      |    17     |      Hello world              |
|    17     |    10     |      |    10     |      Hello                    |
 ------------------------       --------------------------------------------

所以成员10是成员14和17的朋友。而不是只显示成员10的评论,我想显示成员10,14和17的评论。像这样:

        Member Comments                          All Member Comments
 _______________________________        ___________________________________________
| member_id |      comment      |      | member_id |           comment             |
 -------------------------------        -------------------------------------------
|    10     | Hello member # 14 |      |    10     |      Hello member #           |
|    10     |       Hello       |      |    14     |      hey how are you          |
---------------------------------      |    17     |      Hello world              |
                                       |    10     |      Hello                    |
                                       --------------------------------------------

所以我正在尝试mysql_query(“SELECT comments Commenting Table WHERE member_id ='10'ORDER BY member_id DESC”)并做了一堆while循环但这不是很有效。有没有其他方法可以使用多个值选择注释?

2 个答案:

答案 0 :(得分:0)

SELECT *
FROM `Commenting Table`
WHERE member_id=10
OR member id IN (
  SELECT friend_id FROM `Friends Table` WHERE member_id=10
-- Uncomment the following if your Friends Table is asymetrical
--  UNION
--  SELECT member_id FROM `Friends Table` WHERE friend_id=10
)

答案 1 :(得分:0)

您可以按朋友的ID和会员的ID加入表格,然后按会员ID加入表格:

SELECT f.member_id AS user, c.member_id AS commentBy, c.comment AS comment
FROM commentingTable AS c, friendsTable AS f
WHERE c.member_id = f.member_id 
  OR c.member_id = f.friend_id
GROUP BY f.member_id