MySQL union query, order by 2 variables

前端 未结 2 2060
醉酒成梦
醉酒成梦 2021-01-22 10:13

Each table (table1 & table2) has its own DATETIME field.
I\'m trying to catch id\'s of the two tables and order them by their DATETIME field.

Example:

2条回答
  •  温柔的废话
    2021-01-22 10:15

    What you really need to do is to consider your schema more carefully. Consider naming the date time columns the same and then running a query like this - 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
    

    In the SQL fiddle this produces the results closer to what you're looking for. I am still not sure why you need the INNER JOINS on the second query though - there is nothing that you're doing here whcih requires them.

    Here is another method that does not require a changing of the column names, but requires an alias for the sortable columns - 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
    

提交回复
热议问题