【问题标题】:Is it possible to do a three-way join?是否可以进行三向连接?
【发布时间】:2014-10-24 15:02:48
【问题描述】:

我正在使用 Lynda.com 和两本教科书学习数据库和 SQL。我很享受它并取得进步,但复杂的连接让我感到困惑。单连接我可以理解,但我在这篇文章中给出的例子只是让我头晕目眩。

我尝试执行的连接看起来像这样。如果我描述得不好,我很抱歉,我还不知道如何正确描述这些情况。

  • select lastvisit, lastpostid from user where id = 1;
  • select `post.threadid` where `post.postid` =上一行的lastpostid
  • select `thread.title` where `thread.threadid` = 是上一行的threadid

最后,我想返回user.lastvisitthread.title,加入我提到的细节。如果我用伪 SQL 来描述这个连接,我会说 select user.lastvisit where user.id = 1 and thread.title where thread.id = post.threadid from post where post.postid = user.lastpostid from user where id = 1... 这是一口英文。

是否可以使用纯 SQL 来做到这一点?我可以使用编程语言中的脚本来做到这一点,但我觉得必须有某种方法可以使用复杂的连接来做到这一点。

【问题讨论】:

  • 实际上,最终归结为单连接。当你有:A join B join C - 它变成A_joined_with_B join C - 只是想让你的逻辑更容易 - 总是把它想象成一个二进制函数。
  • 加强咖啡的上述说明。加入 A 和 B 后,将其视为您现在要加入 C 的一张表 (AB)。

标签: mysql sql


【解决方案1】:
SELECT user.lastvisit, thread.title
FROM user
LEFT JOIN post ON post.postid = user.lastpostid
LEFT JOIN thread ON thread.threadid = post.threadid
WHERE user.id = 1

如果用户没有帖子,我们会使用左连接

【讨论】:

  • 非常感谢,这是一个完美的答案,真的让它看起来不那么令人生畏。
【解决方案2】:

您可以将其作为 3-way join 进行,也可以检索上次访问信息:

SELECT t.title, u.lastvisit
  FROM thread AS t
  JOIN post   AS p ON t.threadid = p.threadid
  JOIN user   AS u ON p.postid   = u.lastpostid
 WHERE u.id = 1

您几乎可以直接按照您的大纲查询结构执行此操作,但是这不会检索上次访问时间,因此它不是您所追求的。

SELECT thread.title
  FROM thread
 WHERE thread.threadid = 
       (SELECT post.threadid
          FROM post
         WHERE post.postid = (SELECT lastpostid FROM user WHERE id = 1)
       )

【讨论】:

    猜你喜欢
    • 2015-03-05
    • 2019-12-07
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多