如何从sql/Mysql查询中检索数据?

如何从sql/Mysql查询中检索数据?,sql,subquery,inner-join,where-clause,Sql,Subquery,Inner Join,Where Clause,我想从sql查询中检索数据,但无法正确检索数据 我有两张桌子: 表UserPost: id userID postText status 1 abc hello world! 0 2 xyz hello Test! 0 3 abc hello Que! 0 4 qwe hello All! 0 5

我想从sql查询中检索数据,但无法正确检索数据

我有两张桌子:

表UserPost:

id       userID     postText         status
1        abc        hello world!     0
2        xyz        hello Test!      0
3        abc        hello Que!       0
4        qwe        hello All!       0
5        abc        hello Post!      0
6        rty        hello RTY!       0
7        jkl        hello JKL!       0
8        jkl        hello JKL2!      0
9        jkl        hello JKL3!      0
10       jkl        hello JKL4!      0
下表:

id       followerID     followedID         status
1        abc            xyz                 1
2        xyz            qwe                 1
3        abc            rty                 1
4        qwe            abc                 1
5        abc            jkl                 1
我想写一个查询,从用户和跟踪用户中选择帖子

(用户和用户的追随者发布类似“abc”的帖子,以及“abc”关注的所有帖子)

其中UserPost.Status=0,UserFollow.Status=1

我尝试过这一点,但失败了:

SELECT * FROM UserPost INNER JOIN UserFollow 
  ON UserPost.userID = UserFollow.followedID 
    WHERE UserFollow.followerID = 'abc' 
      AND UserFollow.status=1 
        AND UserPost.status=0

// This is not working
我尝试了另一个查询:

select p.*, u.* from ( select * from UserPost 
 where userID = 'abc'  or userID in (select followedID 
 from UserFollow where followedID = 'abc') ) p inner join UserFollow u 
 on u.followedID = p.userID order by p.id
// This query is also not working

我做错了什么?

如果我理解正确,您可以使用
exists

select p.*
from userpost p
where 
    p.status = 0
    and (
        p.userid = 'abc'
        or exists (
            select 1
            from userfollow f
            where f.follower_id = 'abc' and f.followedid = p.userid and f.status = 1
        )
    )

有几种方法可以做到这一点,但以下是非常直观的

SELECT * 
FROM UserPost 
where UserPost.status = 0
and (userID = 'abc'
      or UserID in (select followedID
                    from UserFollow
                    where followerID = 'abc'
                    AND status=1)) 
返回

id  userid  posttext    status
1   abc     hello world!    0
2   xyz     hello Test!     0
3   abc     hello Que!      0
5   abc     hello Post!     0
6   rty     hello RTY!      0
7   jkl     hello JKL!      0
8   jkl     hello JKL2!     0
9   jkl     hello JKL3!     0
10  jkl     hello JKL4!     0


我已经删除了那些相互冲突的dbms标记。将其中一个放回原处,即实际使用的dbms。示例表数据很好,但也指定了预期结果。请在代码问题中给出一个--cut&paste&runnable代码,包括作为代码输入的最小代表性示例;期望和实际输出(包括逐字记录错误消息);标签和版本;清晰的说明和解释。尽可能少地给出代码,即显示为OK的代码,并通过显示为not OK的代码进行扩展。(调试基础。)用于包含DBMS和DDL(包括约束和索引)的SQL,并将其作为格式化为表的代码输入。暂停总体目标的工作,将代码切掉到第一个表达式,没有给出您期望的内容,说出您期望的内容和原因。指定期望的结果,就像您对示例数据所做的那样。请通过编辑而不是评论进行澄清。把你需要的东西放到你的帖子里,而不仅仅是在某个链接上。请仅将图像用于不能表示为文本或扩充文本的内容。包括带有图像的图例/图例和说明。使用编辑功能插入图像/链接。@SoniyaJain:只需将
select p.*
替换为
select count(*)
。你真是个天才,真是个英雄。非常感谢你的帮助!欢迎@SoniyaJain。如果我的答案正确回答了你的问题,那么点击复选标记。。。谢谢