是否可以进行三方联接?

时间:2014-10-24 15:02:49

标签: mysql sql

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

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

  • select lastvisit, lastpostid from user where id = 1;
  • select `post.threadid` where `post.postid` =上一行的最后一个帖子
  • select `thread.title` where `thread.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执行此操作?我可以使用编程语言中的脚本来完成它,但我觉得必须有一些方法可以使用复杂的连接来实现这一点。

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

您可以将其作为3方式加入,也可以检索上次访问信息:

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)
       )
相关问题