什么是正确的SELECT语句?

bɪˈ*_*ɪnə 4 mysql sql inner-join

SELECT *
  FROM notifications
  INNER JOIN COMMENT
    ON COMMENT.id = notifications.source_id
      WHERE idblog IN (SELECT blogs_id
        FROM blogs
        WHERE STATUS = "active")
  INNER JOIN reportmsg
    ON reportmsg.msgid = notifications.source_id
      WHERE uid =: uid
  ORDER BY notificationid DESC
  LIMIT 20;
Run Code Online (Sandbox Code Playgroud)

在这里,我INNER JOIN荷兰国际集团notificationscommentreportmsg; 然后过滤内容WHERE.

但我的问题是,第一INNER JOIN[即与comment],在加入之前notificationscomment,我想匹配notifications.idblogblogs.blogs_id SELECT只有那些行,其中blogs.status = "active".

为了更好地理解上面的代码:

ER图

这里,INNER JOINcomment我想SELECT只有在那些行notifications,其idblog比赛blogs.blogs_id status = "active".

第二个INNER JOINreportmsg需求不被改变.即,它只过滤uid.

Mur*_*dız 5

从下图中可以看出,您可以使用以下方法将其他表合并到通知表LEFT JOIN:

SELECT n.notificationid, n.uid, n.idblog, n.source_id, 
       b.blogs_id, b.status,
       c.id, 
       r.msgid
       -- ... and the other columns you want
FROM notifications n
LEFT JOIN blogs b ON b.blogs_id = n.idblog AND b.STATUS = "active" AND n.uid =: uid
LEFT JOIN comment c ON c.id = n.source_id    
LEFT JOIN reportmsg r ON r.msgid = n.source_id
ORDER BY n.notificationid DESC
LIMIT 20;
Run Code Online (Sandbox Code Playgroud)


SQL JOINS

希望这可以帮助...

  • 如果你有'WHERE b.STATUS ="有效"`这就有了`LEFT JOIN blogs b`没有意义......这有效地将它恢复为`INNER JOIN` (2认同)