使用同一查询中的另一个选择从表中选择

时间:2019-01-18 07:43:27

标签: php mysqli

mysql场景:

表:posts => postIduserId postContent; 表格:friends => friendIduserAuserB

查询:

SELECT *
FROM posts
WHERE userId IN (SELECT * FROM friends WHERE userA = {$_SESSION['userId']} OR userB = {$_SESSION['userId']});
  

mysqli_fetch_assoc()期望参数1为mysqli_result,给定布尔值

查询中我缺少什么?

2 个答案:

答案 0 :(得分:0)

请尝试这个

SELECT *
FROM statements 
WHERE userId IN (SELECT userId FROM friends WHERE userA = {$_SESSION['userId']} OR userB = {$_SESSION['userId']});

答案 1 :(得分:0)

编辑: 有一个子查询

SELECT *
FROM posts 
WHERE userId IN (
    SELECT 

    CASE 
        WHEN userA = {$_SESSION['userId']} THEN userB
        ELSE userA
    END as user

    FROM friends WHERE userA = {$_SESSION['userId']} OR userB = {$_SESSION['userId']}
);

旧答案:

我搜索了一个更好的解决方案,但我认为它可以用于两个子查询:

SELECT *
FROM posts 
WHERE userId IN (SELECT userB FROM friends WHERE userA = {$_SESSION['userId']}) OR userId IN (SELECT userA FROM friends WHERE userB = {$_SESSION['userId']});

但是请考虑使用PDO来提高安全性