简体   繁体   English

合并两个表(按日期排序)

[英]Combining two tables, ordering by date, with limit

I have two tables posts and replies . 我有两个表的postsreplies What I'm currently doing is only displaying the 25 most recent posts on the main page of my website with the following query: 我目前正在做的只是在我网站的主页上显示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

What I want to do is get the 25 most recent posts and replies (combined). 我想做的是获取25个最新postsreplies (合并)。 For example, I want to output this on the main page: 例如,我要在主页上输出:

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.

How would I do this? 我该怎么做?

You can use a union query , then limit the results of that. 您可以使用并集查询 ,然后限制其结果。 I'm assuming your replies table has the same structure: 我假设您的回复表具有相同的结构:

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

If you have same structure for replies table, you can use union like below 如果您的回复表具有相同的结构,则可以使用如下所示的并集

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM