如何获取与我的不匹配的mysql查询的id?

时间:2018-02-21 00:47:14

标签: php mysql

我有以下mysql查询:

$get_friends_posts = "SELECT * FROM users_friendships
                      WHERE userid1 != $myid and userid2 = $myid 
                      or userid2 != $myid and userid1 = $myid";

$friendpost = mysqli_query($mysql, $get_friends_posts);

$ myid是登录并观看此脚本的用户的唯一ID。现在,我希望通过一张支票或一些与我不相符的东西获得身份证,就像友谊的对手一样。

在数据库中有id,userid1和userid2的行。

1 个答案:

答案 0 :(得分:0)

此查询将从userid表中返回单个列(users_friendships),其中$myiduserid1userid2。我假设没有userid1userid2相同值的行。

SELECT
CASE WHEN userid1 = $myid THEN userid2 ELSE userid1 END AS userid
FROM users_friendships
WHERE userid1 = $myid OR userid2 = $myid

如果要使用这些结果从另一个表中获取数据,可以执行以下操作:

SELECT
posts.*
FROM posts
WHERE posts.userid IN
(
    SELECT
    CASE WHEN userid1 = $myid THEN userid2 ELSE userid1 END AS userid
    FROM users_friendships
    WHERE userid1 = $myid OR userid2 = $myid
)

或者,如果您需要有关用户和帖子的额外信息,则需要更复杂的需求,您可以执行以下操作:

SELECT
    users.name,
    posts.date,
    posts.title
FROM users_friendships
INNER JOIN users ON users.userid = CASE WHEN users_friendships.userid1 = $myid THEN users_friendships.userid2 ELSE users_friendships.userid1 END
INNER JOIN posts ON posts.userid = CASE WHEN users_friendships.userid1 = $myid THEN users_friendships.userid2 ELSE users_friendships.userid1 END
WHERE users_friendships.userid1 = $myid OR users_friendships.userid2 = $myid
ORDER BY posts.date DESC