0

I have 2 tables:

Friends

  ID  |  Profile  |  Check
------+-----------+---------
  int |    int    |   bool

Where ID is person who sent original friend request, Profile is ID of person request was sent to, and Check is 0 = request pending; 1 = request accepted.

Messages

  OwnerID  |  ...
-----------+-------
    int    |  ...

Where OwnerID is ID of member who wrote the message.

So basically, what I am looking at is first:

select all rows from friends_list table where ID or Profile is equal to the memberID cookie. BUT heres my plight: If I send another user a friend request, then my ID is placed in the ID field and their ID is placed in the Profile field of the friend_list table. But if another user requests a friend request from me, then my ID would go into the Profile field and theirs would go in the ID field.

So, I would have a row where ID = 1, and Profile = 2. And the next row would be ID = 3 and Profile = 1. Now, both users with IDs 2 and 3 are friends of mine (ID 1), So I need to show all messages from 1, 2, and 3 (mine and my two friends) where check = 1

4

1 回答 1

1

你想要的是这样的:

(
    SELECT m.*
    FROM Messages m
    INNER JOIN Friends f ON m.OwnerID = f.ID
    WHERE f.Profile = ?
) UNION (
    SELECT m.*
    FROM Messages m
    INNER JOIN Friends f ON m.OwnerID = f.Profile
    WHERE f.ID = ?
)

您需要查看这两个单独的查询,我认为您不能使用 s的组合来明智地做到这一点JOIN

假设您使用的是 MySQL,这不应该返回重复的行,因为默认修饰符UNIONDISTINCT. 其他 RDBMS 引擎可能要求您明确说明这一点或使用其他一些解决方法(例如GROUP BY实际消息 ID 上的 a)。

您可能还想在两个查询m.Check = 1的子句中添加一个条件WHERE,以确保您只收到已接受好友请求的消息。

显然,上面的内容旨在用作准备好的语句,其中两个占位符将替换为相同的数据 - memberIDcookie。

于 2013-04-23T09:47:44.270 回答