通过id从多个表中提取并按创建日期排序

时间:2014-04-17 17:42:17

标签: php mysql

我试图用单个查询提取用户的活动。我需要用一个查询来完成它,所以我可以使用zend paginator。

我有5个表:usersrepliesthreadswiki_articleswiki_article_revisions。每个表都有2个常用列created_bycreated_on

我已尝试使用left join,但我认为它返回的内容不正确,而且我无法通过created_on

订购所有活动

以下是我尝试过的加入:

SELECT * FROM `users` u
LEFT join `replies` r ON u.id = r.created_by
LEFT join `threads` t ON u.id = t.created_by
LEFT join `wiki_articles` wa ON u.id = wa.created_by
LEFT join `wiki_article_revisions` war ON u.id = war.created_by
WHERE (u.`name` = 'CGeorges') 

1 个答案:

答案 0 :(得分:0)

我的思维过程是错误的。我应该使用UNION,比如:

(SELECT id, name, created_on FROM users WHERE id = 1)
UNION
(SELECT id, name, created_on FROM threads WHERE created_by = 1)
UNION
(SELECT id, content, created_on FROM replies WHERE created_by = 1)
UNION
(SELECT id, title, created_on FROM wiki_articles WHERE created_by = 1)
ORDER by created_on DESC