合并2个MySQL查询并按时间戳排序结果

时间:2012-01-31 21:17:22

标签: mysql sql database

我有一个查询返回用户的所有流帖子(带注释):

SELECT  *
FROM   (SELECT *
       FROM stream_ps
       ORDER BY stream_ps_timestamp DESC
       LIMIT $offset, $limit) sps
        JOIN user_profiles
          ON user_id = sps.stream_ps_author_id
        LEFT JOIN (SELECT stream_cm_id,
                          stream_cm_author_id,
                          stream_id_fk,
                          stream_ps_id_fk,
                          stream_cm_text,
                          stream_cm_timestamp,
                          first_name as comm_first_name,
                          last_name as comm_last_name,
                          facebook_id as comm_fb_id,
                          picture as comm_picture
                    FROM  stream_cm
                    JOIN  user_profiles
                      ON  user_id = stream_cm_author_id) AS c
          ON sps.stream_ps_id = c.stream_ps_id_fk
ORDER   BY sps.stream_ps_id DESC, c.stream_cm_id ASC

以及另一个返回所有论坛帖子的查询:

SELECT  qa.*,
        user_profiles.*,
        n.pid,
       Ifnull(n.ans_count, 0) AS ans_count
FROM  (SELECT * FROM forum_qa
       ORDER BY forum_qa_type,forum_qa_timestamp DESC
       LIMIT $offset, $limit) qa
       LEFT JOIN user_profiles
         ON user_id = qa.forum_qa_author_id
       LEFT JOIN (SELECT forum_qa_parent_id AS pid,
                         COUNT(*)           AS ans_count
                  FROM   forum_qa
                  WHERE  forum_qa_parent_id IS NOT NULL
                  GROUP  BY forum_qa_parent_id) AS n
         ON qa.forum_qa_id = n.pid
WHERE  qa.forum_qa_type = 1
ORDER  BY qa.forum_qa_timestamp DESC

我想将两者合并到一个查询中并对结果重新排序,以便它们按时间顺序排列(即时间戳DESC,最近显示的是最近的)。

因此,最终结果将显示最新条目的主题,无论是帖子还是论坛。

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:1)

由于表具有不同的字段,如果您确实需要在SQL中进行排序,则可以将两个结果集合并为一个包含两个字段的大表。

的内容
SELECT * FROM (
    SELECT col1, col2, null, null, time_stamp FROM table1
    UNION
    SELECT null, null, colA, colB, time_stamp FROM table2
) entries
ORDER BY time_stamp DESC
LIMIT $offset, $limit

答案 1 :(得分:0)

我认为您正在寻找UNION

答案 2 :(得分:0)

听起来你想要UNION。要使用UNION,您需要确保列匹配;来自文档

  

UNION用于组合多个SELECT语句的结果   到一个结果集。

     

第一个SELECT语句中的列名用作   返回结果的列名称。列出的选定列   每个SELECT语句的相应位置应该相同   数据类型。

基本用法是这样的

SELECT id, value FROM tableA
UNION
SELECT id, value FROM tableB
ORDER BY id

因此,如果您的两个查询的字段列表在类型和顺序上匹配,则可以将它们简单地放在一起。