结合两个表,按日期排序,限制

时间:2014-03-03 00:32:52

标签: php mysql sql mysqli

我有两张表postsreplies。我目前正在做的只是在我的网站主页上显示25个最新的posts,并提供以下查询:

SELECT p.post_id
     , p.user_id
     , p.message
     , p.datetime
     , u.username 
  FROM posts p 
  LEFT 
  JOIN users u 
    ON p.user_id = u.user_id 
 ORDER 
    BY p.datetime DESC
 LIMIT 25

我想要做的是获取最近的25 postsreplies(合并)。例如,我想在主页面上输出:

User A posted "blah blah blah" on Feb. 3, 2014.
User B posted "yeah yeah yeah" on Feb. 2, 2014.
User A replied "this is a reply" on Feb. 2, 2014.
User C posted "some post" on Feb. 1, 2014.

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用union query,然后限制其结果。我假设您的回复表具有相同的结构:

SELECT results.*, u.username FROM (
    SELECT p.post_id, p.user_id, p.message, p.datetime FROM posts p
    UNION    
    SELECT r.post_id, r.user_id, r.message, r.datetime FROM replies r 
) as results  
LEFT JOIN users u ON results.user_id = u.user_id
ORDER BY results.datetime DESC LIMIT 25

答案 1 :(得分:0)

如果您的回复表具有相同的结构,则可以使用下面的联合

SELECT p.post_id, p.user_id, p.message, p.datetime AS postTime, u.username FROM posts p LEFT JOIN users u ON p.user_id = u.user_id 
UNION
SELECT r.reply_id, r.user_id, r.message, r.datetime AS postTime, u.username FROM replies r LEFT JOIN users u ON r.user_id = u.user_id
ORDER BY postTime DESC LIMIT 25