MySQL UNION query with condition

I had 2 bells of festivals and events such as

the festival

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 

events

 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 

A page with the latest updates is displayed in my application, and by clicking on each list, it will be redirected to the corresponding event or festival.

For this, I had the following request

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

This will return a table like

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

But my question is: I need another column to understand that the row represents an event or festival .. Something like ths

 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 

Please help Thanks in advance

+4
source share
2 answers
 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 
+10
source

That should do the trick

 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 
+3
source

Source: https://habr.com/ru/post/1403587/


All Articles