S
S
Sergey2015-04-24 14:39:02
MySQL
Sergey, 2015-04-24 14:39:02

How to correctly compose a query using the UNION operator?

There are two tables:
1) comment

id | task_id | date
1  |    1    |   1
2  |    1    |   2
3  |    2    |   2

2) deal
id | task_id | date
11 |    1    |   3
21 |    1    |   2

I need to write a query that would combine records by the "task_id" field and sort by the "date" field, and as a result I need to understand which record is from which table, i.e. I will need to rename the id or display some flag by which I could find out.
I wrote this query:
(SELECT C.id, date FROM comment AS C WHERE C.task_id = 1)
UNION
(SELECT D.id, date FROM deal AS D WHERE D.task_id = 1)
ORDER BY date

Which outputs:
id | date
1  |   1
22 |   1
2  |   2
11 |   3

But I can’t rename the columns so that it would be clear from which table the data is

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
ldv, 2015-04-24
@frost18

(SELECT C.id, date,  'comment' as tname FROM comment AS C WHERE C.task_id = 1)
UNION
(SELECT D.id, date,  'deal' as tname FROM deal AS D WHERE D.task_id = 1)
ORDER BY date

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question