检查结果计数

时间:2018-04-19 02:50:29

标签: mysql sql

我正在开发一个需要从我的数据库中获取帖子的项目。我试图获取用户和其他用户发布的帖子,除非他们是私人的。

我的SQL查询是

SELECT . . .,COUNT(F.user_id) AS is_following FROM posts AS P INNER JOIN users AS U ON U.id = P.user_id LEFT JOIN followers AS F ON F.user_id = :userid AND F.following_id = U.id WHERE *If matches search* AND U.private = 0 OR U.id = :userid OR is_following = 1 ORDER BY. . .

我选择用户跟踪海报的位置并计算它,如果0表示他们没有跟随,1表示1结果,因此,跟随他们。此外,我正在检查私人是否为0表示该帐户是公开的。

问题是当我有is_following = 1时它会返回没有结果如果我删除它虽然它确实返回结果但不是全部。

表格

users: id|username|private|...
followers: userid|followingid
posts: id|userid|body

内容:

用户:

user1|test1|1 (This is the user running the request)
user2|test2|1
user3|test3|1

追随者:

user1|user2 (User searching follows test2)

帖子:

post1|user1|HelloWorld
post2|user2|Hello_World
post3|user3|Hello-World

预期的结果是返回post1和post2而不是post3,因为user3是私有的(private设置为true / 1)而user1没有跟随test3,但是它应该显示user2的帖子,因为user1跟随user2

2 个答案:

答案 0 :(得分:1)

当你有{ "data" : { "2" : 2, "-LAHu2g4g2S9UBRUSzYy" : "ada", "-LAHuvLqM-14e4tC39fr" : "0818088325", "-LAIU21b5n9JKgyi9Yct" : "2", "asd" : "asd" } } 条件时它没有返回结果的原因是你试图在WHERE子句中使用MySQL不允许的别名。将is_following替换为is_following,它应该有效。

答案 1 :(得分:1)

如果我理解正确的话。

有两种群体

  1. private 0 表示该帐户是公开的
  2. private 1 需要在关注者表上找到以下用户。
  3. 一个简单的方法,你可以做两个查询一个是私有 0 ,另一个是私有 1 ,然后使用UNION ALL结合这些。 / p>

    SELECT * FROM 
    (
      SELECT p.*
      FROM users as u 
      INNER JOIN posts AS P ON p.userid = u.id  
      WHERE u.private = 0 
      UNION ALL 
      SELECT p.*
      FROM users as u 
      INNER JOIN posts AS P ON p.userid = u.id  
      RIGHT JOIN followers AS F ON F.followingid = u.id
      WHERE u.private = 1 AND f.userid = :userid 
    )t
    

    或使用exists进行检查

    SELECT p.*
    FROM users as u 
    INNER JOIN posts AS P ON p.userid = u.id  
    WHERE u.private = 0 OR exists 
    (
        SELECT 1 
        FROM followers AS F LEFT JOIN users ON F.followingid = users.id
        WHERE u.id = users.id 
        and users.private 
        and f.userid = :userid 
    )
    

    sqlfiddle:http://sqlfiddle.com/#!9/50ef05/1

    修改

    如果你想让用户成为或不是is_following,你可以这样做。

    然后您可以在外is_following子句中找到哪个用户where

    SELECT * FROM 
    (
      SELECT p.*,0 as 'is_following'
      FROM users as u 
      INNER JOIN posts AS P ON p.userid = u.id  
      WHERE u.private = 0 
      UNION ALL 
      SELECT p.*,1 
      FROM users as u 
      INNER JOIN posts AS P ON p.userid = u.id  
      RIGHT JOIN followers AS F ON F.followingid = u.id
      WHERE u.private = 1 AND f.userid = 'user1'
    )t
    /*where is_following = 1*/
    

    sqlfiddle:http://sqlfiddle.com/#!9/b7f6c/10