doushengyou2617 2013-10-26 11:14
浏览 48

评论和回复,加入3表查询

I have been searching now for a while, but still did not find an optimal solution. I have three tables: posts, membership and comments. I want to have a Comment and reply system.

These are my tables:

Main posts:

post_id | image_url | image_thumb_url | title | text | date | sender_id 

Membership:

user_id | username | pw | email | 

Comments (replies) to posts:

com_id | comment | post_id_fk | user_id_fk | ip | date

I currently have a query for retrieving the posts with the membership data:

SELECT * FROM `posts`
LEFT JOIN `membership` ON `posts`.`sender_id` = `membership`.`user_id`
UNION SELECT * FROM `posts`
      RIGHT JOIN `membership` ON `posts`.`sender_id` = `membership`.`user_id`
      ORDER BY `post_id` DESC LIMIT $limit $start;

I now want to add the replies to each posts, containing the membership data. Does anyone have suggestion or perhaps a better solution ?

  • 写回答

1条回答 默认 最新

  • dongyu1979 2013-10-26 13:41
    关注
    SELECT * FROM posts AS P
    LEFT JOIN comments AS C
    ON P.post_id = C.post_id_fk
    LEFT JOIN membership AS POST_MEMBER
    ON POST_MEMBER.user_id = P.sender_id
    LEFT JOIN membership AS REPLY_MEMBER
    ON REPLY_MEMBER.user_id = C.user_id_fk 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程