连接和排序两个具有相同列的表

时间:2012-11-16 16:39:18

标签: php mysql

我正在尝试将这两个表合并,然后按一列(stamp)对其进行排序,并对第二个表的id字段进行别名处理。我尝试过加入,合并,但似乎没有任何效果。我也试图按mm

对它们进行分组

note

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

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 |

我认为查询可行:

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

预期结果

  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 |

我甚至不知道这是否可行。我找到了一种在PHP中对此进行排序的方法,但如果可以在mySQL中完成它会更容易。感谢。

1 个答案:

答案 0 :(得分:0)

我认为你的意思是这个,请注意相同的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