简体   繁体   中英

Joining and Ordering two tables that have same columns

I am trying to combine these two tables then order it by one column ( stamp ), and aliasing the second table's id field. I've tried joins, merges, but nothing seems to work. I am also trying to group them by the mm

Table note

  id | mm |   stamp    |
==========================
  1  | 5  | 2009-12-11 |
  2  | 33 | 2010-09-10 |
  3  | 22 | 2011-07-08 |
  4  | 1  | 2012-05-06 |

Table note_admin

  id | mm |   stamp    |
==========================
  1  | 5  | 2009-08-15 |
  2  | 5  | 2011-11-11 |
  3  | 5  | 2012-01-08 |
  4  | 35 | 2012-02-06 |

Query I thought would work:

(SELECT * FROM note WHERE mm=5)
UNION
(SELECT id AS a_id, mm, stamp FROM note_admin WHERE mm=5) 
ORDER BY stamp DESC

Expected Result

  id | a_id | mm |   stamp    |
================================
     |   3  | 5  | 2012-01-08 |
     |   2  | 5  | 2011-11-11 |
  1  |      | 5  | 2009-12-11 |
     |   1  | 5  | 2009-08-15 |

I don't even know if this is possible. I found a way to sort this in PHP but it would be much easier if it can be done in mySQL. Thanks.

我认为您的意思是,请注意相同的4列名称(尽管不确定顺序):

(SELECT a_id as NULL, note.* FROM note WHERE mm=5) UNION (SELECT id AS a_id, NULL as id, mm, stamp FROM note_admin WHERE mm=5) ORDER BY stamp DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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