按日期排序行从多个表中收集?

时间:2018-05-23 20:43:29

标签: mysql sql mariadb

例如,我有以下表格:

表一:

 -------------------------
|   UID    |    Date      |
 -------------------------
|   John   |     2        |
|   mark   |     4        |
 -------------------------

表二:

 -------------------------
|   UID    |    Date      |
 -------------------------
|   smith  |     1        |
|   Nork   |     3        |
 -------------------------

我期待的结果是按日期排序:

 ----------
|   smith  |
|   John   |
|   Nork   |
|   mark   |
 ----------

我试过:

(SELECT UID
  FROM table1 
  ORDER BY DATE DESC 
  LIMIT 16) 
UNION
(SELECT UID 
  FROM table2 
  ORDER BY DATE DESC 
  LIMIT 16)

但结果它打印的是它先获取table1及其所有行,然后转到table2。

2 个答案:

答案 0 :(得分:1)

在查询中,您可以对表中的每个结果集进行单独排序,以对检索到的行应用限制。

如果您想保留合并结果集的顺序,则需要再次应用它。使用子查询来实现此目的。您需要进一步传递date列才能执行此操作,因此我将UNION更改为UNION ALL,因为我们不需要在此级别应用它。在更高级别添加DISTINCT将处理唯一值。

SELECT DISTINCT UID
FROM (
  (SELECT UID, DATE FROM table1 ORDER BY DATE DESC LIMIT 16)
  UNION ALL
  (SELECT UID, DATE FROM table2 ORDER BY DATE DESC LIMIT 16)
  ) t
ORDER BY DATE

答案 1 :(得分:0)

我尝试使用mysql db这样的数据。它工作得很好。请试试这个:

  SELECT t.UID FROM
         (SELECT t1.UID,t.DATE FROM table1 t1 
            UNION ALL
          SELECT t2.UID,t.DATE FROM table2 t2 
          ) as t
        ORDER BY t.DATE ASC