Complex SQL query, checking column values in multiple tables

微笑、不失礼 提交于 2019-12-13 04:17:23

问题


I have a pretty huge SQL query to check for notifications, and I have several different types of notifications in the table, IE: posts, likes, comments, photoComments, photoLikes, videoLikes, etc. (Always adding more to it) And I have come into a problem, I'm not really sure how to best do this anymore. Thus far the way I have done it is working perfectly, and really quite easy to add to, however this one notification Type I have to check more than just one other table, I have to check two others and I haven't been able to get it to work.

So here it is: (This is only one part of my huge query, the only relevant part really)

n.uniqueID = ANY (
              SELECT photos.id
              FROM photos INNER JOIN posts ON (photos.id=posts.post)
              WHERE photos.state=0
              AND posts.state=0 
              AND posts.id = ANY (
                                   SELECT likes.postID FROM likes
                                   INNER JOIN posts ON (posts.id=likes.postID)
                                   WHERE likes.state=0 AND posts.state=0
                                  )
                )

So basically all I really need to do is check the state columns in each table because that says whether or not it is deleted or not (if it's not 0 then it's deleted and shouldn't be returned) So it would be like:

IF photos.state=0 AND posts.state=0 AND likes.state=0 return it.

  • n.uniqueID, posts.post, and photo.id will all be the same value.
  • posts.id and likes.postID will also be the same value.

My issue is that it doesn't seem to be checking the likes.state, I don't think.


回答1:


I think you just want to join the three tables together in a single query:

n.uniqueID = ANY (
              SELECT photos.id
              FROM photos INNER JOIN
                   posts
                   ON photos.id=posts.post inner join
                   likes
                   on posts.id = likes.postId
              WHERE photos.state=0 and
                    posts.state=0 and
                    likes.state = 0
                  )

Your logic is not to return when there is a like or post with the state of 0. It seems to be that all the likes and posts have a state of zero. For this, do an aggregation with a having clause:

n.uniqueID = ANY (
              SELECT photos.id
              FROM photos INNER JOIN
                   posts
                   ON photos.id=posts.post inner join
                   likes
                   on posts.id = likes.postId
              where photos.state = 0
              group by photos.id
              having MAX(posts.state) = 0 and MAX(likes.state) = 0


来源:https://stackoverflow.com/questions/14222605/complex-sql-query-checking-column-values-in-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!