带有条件的MySQL UNION查询

时间:2012-03-27 06:13:45

标签: php mysql mysql-management

我有2个列的节日和活动,比如

id  |   name     | modified_date
-----------------------------------
12  | fest 1     |  2012-03-14 17:45:40
13  | fest 2     |  2012-03-14 17:45:40
15  | fest 4     |  2012-03-14 17:45:40
11  | fest 5     |  2012-03-14 17:45:40

活动

id  |   name     | modified_date
-----------------------------------
14  | envt 1     |  2012-03-14 17:45:40
15  | envt 2     |  2012-03-14 17:45:40
16  | envt 4     |  2012-03-14 17:45:40
17  | envt 5     |  2012-03-14 17:45:40

我的应用程序中有一个页面显示最近更新,通过单击每个列表,它将重定向到相应的事件或节日。

为此,我有以下查询

select id,name,modified_date from events
UNION
select id,name,modified_date from festival
order by modified_date desc

这将返回一个类似

的表格
id  |   name     |  modified_date
-------------------------------------
12  | fest 1     |  2012-03-14 17:45:40
13  | fest 2     |  2012-03-14 17:45:40
--------------------------------------------

但是我的问题是我需要再提出一个专栏来理解行代表一个事件或节日......就像那些

id  |   name     |  modified_date         |  type
---------------------------------------------------
12  | fest 1     |  2012-03-14 17:45:40   |  festival
15  | evnt 2     |  2012-03-14 17:45:40   |  event 

请帮忙 提前致谢

2 个答案:

答案 0 :(得分:10)

select id, name, modified_date, 'event' as type
from events 

UNION 

select id, name, modified_date, 'festival' as type
from festival 
order by modified_date desc

答案 1 :(得分:3)

这应该可以解决问题

select id,name,modified_date, 'event' AS type from events
UNION
select id,name,modified_date, 'festival' AS type from festival order by modified_date desc