小编典典

MySQL联合查询,按2个变量排序

sql

每个表(表1和表2)都有其自己的DATETIME字段。
我正在尝试捕获两个表的ID,并按其DATETIME字段对其进行排序。

例子:

Table 1                        Table 2
------------                 -------------
id |  datetime1               id | table1id  | datetime2
------------------------      -----------------------
1  |  2014-09-21 20:31:26     1  | 2         | 2014-09-21 20:31:29
2  |  2014-09-21 20:31:27     2  | 3         | 2014-09-21 20:31:30
3  |  2014-09-21 20:31:28

Table 3                      
------------               
id |  user               
------------------------   
2  |  phil                
3  |  nathalie

我的输出未通过以下查询正确排序:

SELECT *
FROM (
    SELECT 
    1 AS selection, 
    table1.id, table1.datetime1, 
    table2.datetime2 
    table3.user 
    FROM Table1 
    LEFT OUTER JOIN table2 
    ON table1.id = table2.table1id
    LEFT OUTER JOIN table3
    ON table1.id = table3.id

    UNION ALL

    SELECT 
    2 AS selection, 
    table1.id, table1.datetime1, 
    table2.datetime2 
    table3.user 
    FROM Table1 
    INNER JOIN table2 
    ON table1.id = table2.table1id
    INNER JOIN table3
    ON table1.id = table3.id
) AS query
ORDER BY table1.datetime1 DESC, table2.datetime2 DESC

所需数据:
来自表2 id:2、1,
来自表1 id:3、2、1
因此:2、1、3、2、1

////编辑

对于可能会遇到冗长而复杂的MySQL请求的人们,请在PhpmyAdmin中尝试一下!它会告诉您错误!

////编辑


阅读 193

收藏
2021-04-14

共1个答案

小编典典

您真正需要做的是更仔细地考虑您的架构。考虑将日期时间列命名为相同的名称,然后运行这样的查询-http:
//sqlfiddle.com/#!2/a3b4c/7/0

SELECT selection, id, datetimefoo, user FROM (
  SELECT 
    1 AS selection, 
    table1.id, table1.datetimefoo, 
    table3.user 
    FROM table1 
    LEFT OUTER JOIN table2 
    ON table1.id = table2.table1id
    LEFT OUTER JOIN table3
    ON table1.id = table3.id


  UNION

  SELECT 
    2 AS selection, 
    table1.id, table1.datetimefoo, 
    table3.user 
    FROM table1 
    INNER JOIN table2 
    ON table1.id = table2.table1id
    INNER JOIN table3
    ON table1.id = table3.id

  ) AS T2
ORDER BY datetimefoo DESC

在SQL提琴中,这将产生与您要查找的结果更接近的结果。我仍然不确定为什么您需要在第二个查询上使用INNER JOINS-在这里您不需要执行任何操作。

下面是不需要的列名的变化的另一种方法,但需要排序的列的别名-
http://sqlfiddle.com/#!2/ec4bc/3/0

SELECT * FROM (
  SELECT 
    1 AS selection, 
    table1.id, table1.datetimefoo AS sort_date, -- alias on first table's date
    table2.datetimebar,
    table3.user 
    FROM table1 
    LEFT OUTER JOIN table2 
    ON table1.id = table2.table1id
    LEFT OUTER JOIN table3
    ON table1.id = table3.id


  UNION

  SELECT 
    2 AS selection, 
    table1.id, table1.datetimefoo,
    table2.datetimebar AS sort_date, -- alias on second table's date
    table3.user 
    FROM table1 
    INNER JOIN table2 
    ON table1.id = table2.table1id
    INNER JOIN table3
    ON table1.id = table3.id

  ) AS T2
ORDER BY sort_date DESC
2021-04-14