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

帖子表包含以下列:

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


股份表中有

postid, shareuserid, dateshared,likes


用户表具有

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


sharepost中的postid引用了post表中的postID。
userID和shareuserid都引用相同的用户表。
我想检索原始用户以及共享该帖子的用户。

发布表的示例数据是,
enter image description here

股份表的样本数据是
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


我希望从发布表中检索原始用户,并从sharepost表中检索共享该帖子的用户,但我只会得到共享用户的名称。

enter image description here

最佳答案

以下应该可以解决问题:

    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的任何引用。不确定是否是错字?

08-28 02:41