这是我的问题:我有3个MySql表,代表:用户发布照片,用户发布视频,用户发帖评论,我需要查看用户最近的10(20,30,40 ......)次活动.例如在照片表中可能由以下组成:
user_id | photo_id | photo_path | photo_name | date_added 5 | 18 | /photos | pht_18.png | 2009-02-12 5 | 21 | /photos | pht_21.png | 2009-02-15 5 | 29 | /photos | pht_29.png | 2009-03-30
视频表
user_id | video_id | video_url | date_added 5 | 36 | youtube.com/... | 2009-01-09 5 | 48 | youtube.com/... | 2009-02-18 5 | 90 | youtube.com/... | 2009-03-19
评论表
user_id | comment_id | comment | date_added 5 | 6 | hi! | 2009-02-11 5 | 11 | great photo | 2009-02-13 5 | 19 | nice shot! | 2009-03-28
如您所见,3个表具有不同数量的属性,那么我该如何进行联合?并且在获取查询结果时,我如何理解它属于哪个表?
因此,在用户个人资料页面中,我想通过以下方式显示他最近按DATE DESC订购的课程:
2009-09-01: user posted a video 2009-11-02: user posted a comment 2009-12-02: user posted a photo 2009-13-02: user posted a comment 2009-15-02: user posted a photo 2009-18-02: user posted a video 2009-19-03: user posted a video 2009-28-03: user posted a comment 2009-30-03: user posted a photo
有人可以帮我吗?
MySQL UNION查询可以在这里工作:
(SELECT `user_id`, `date_added`, 'photo' AS `type` FROM `photos` WHERE `user_id` = uid) UNION (SELECT `user_id`, `date_added`, 'video' AS `type` FROM `videos` WHERE `user_id` = uid) UNION (SELECT `user_id`, `date_added`, 'comment' AS `type` FROM `comments` WHERE `user_id` = uid) ORDER BY `date_added` DESC;
然后你最终得到一个结果集
user_id | date_added | type 5 | 2009-01-03 | photo 5 | 2008-12-07 | video 5 | 2008-11-19 | comment
等等.(user_id
当然,如果你愿意,你可以不用SELECT)