【问题标题】:Join three tables in mysql database连接mysql数据库中的三个表
【发布时间】:2019-07-15 14:42:44
【问题描述】:

我正在尝试在 mysql 中加入三个表。我有三个表,分别称为 post、sharepost 和 user。我想加入 sharepost 和 user 来检索分享帖子的用户的名字和姓氏,我想加入 post 和 user 来检索帖子原始用户的名字和姓氏以及其他列。

post 表有以下列,

postID, title, description, userID, dateposted,likes.

sharepost 表有,

postid, shareuserid, dateshared,likes

用户表有,

userID, firstname, lastname, datejoined, email, password, birthdate.

sharepost 中的 postid 引用 post 表中的 postID。 userID 和 shareuserid 都引用同一个用户表。 我想检索原始用户和分享帖子的用户。

post 表的样本数据是, enter image description here

sharepost 表的样本数据是, enter image description here

用户表的样本数据是, enter image description here

以下查询可以检索分享帖子的用户的名字和姓氏,

SELECT P.postID,P.userID, P.title, P.description, S.shareuserID,
U.firstname, S.dateShared, S.likes from sharepost S join post P 
on S.postID=P.postID join user U on S.shareuserID=U.userID

我希望从 post 表中检索原始用户,并从 sharepost 表中检索共享帖子的用户,但我只获取共享用户的名称。

enter image description here

【问题讨论】:

  • 请提供示例数据和预期结果。

标签: mysql database


【解决方案1】:

以下应该可以解决问题:

    SELECT p.postID,
           p.userID AS author_id,
           p.title,
           p.description,
           sp.shareuserid AS sharer_id,
           sp.dateShared,
           sp.likes,
           u1.firstname AS author_forename,
           u1.lastname AS author_surname,
           u2.firstname AS sharer_forename,
           u2.lastname AS sharer_surname
      FROM post p
INNER JOIN sharepost sp ON p.id = sp.postid
INNER JOIN user u1 ON p.userID = u1.userID
INNER JOIN user u2 ON sp.shareuserid = u1.userID

值得注意的是,我在您的架构中看不到对likes 的任何引用。不知道是不是笔误?

【讨论】:

  • 因此,每当需要将一个表与另外两个表连接时,我们必须提供唯一的别名,尽管它是同一个表?
  • 当您在多个字段中加入同一个表时,是的。
  • 为什么不能用join on代替inner join on?有区别吗?
  • 它不返回任何东西。
  • 可以的。 JOIN ONINNER JOIN ON 是一样的。
【解决方案2】:

感谢@BenM 的回答,我设法将我的查询修改为以下返回我的预期结果,

SELECT P.postID,
          P.userID, 
          P.title, 
          P.description, 
          S.shareuserID, 
          U.firstname AS sharer_name, 
          U1.firstname as author_name, 
          S.dateShared, S.likes 
     from sharepost S 
join post P on S.postID = P.postID 
     join user U on S.shareuserID = U.userID 
     join user U1 on P.userID=U1.userID

【讨论】:

    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 2014-02-24
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多