MajAfy
MajAfy

Reputation: 3097

Select records from 2 tables

I have 2 tables in MySQL, in both of these tables I have id, title, date and some another fields, the name of one table is news and another table is gallery .

    Table news :
    id   |  title   |   date       |  ...
   ------+----------+--------------+-------
    1    | TestN 1  |  2012-12-12  | ...
    2    | TestN 2  |  2012-12-14  | ...
    3    | TestN 3  |  2012-12-14  | ...



     Table gallery :
    id   |  title   |   date       |  ...
   ------+----------+--------------+-------
    1    | TestG 1  |  2012-12-10  | ...
    2    | TestG 2  |  2012-12-12  | ...
    3    | TestG 3  |  2012-12-15  | ...

I want to know how can I select id, title records from both tables order by date? Is it possible?

Like this:

   Result :
    id   |  title   |   date       |  ...
   ------+----------+--------------+-------
    1    | TestG 1  |  2012-12-10  | ...
    1    | TestN 1  |  2012-12-12  | ...
    2    | TestG 2  |  2012-12-12  | ...
    2    | TestN 2  |  2012-12-14  | ...
    3    | TestN 3  |  2012-12-14  | ...
    3    | TestG 3  |  2012-12-15  | ...

Upvotes: 4

Views: 3667

Answers (3)

Mohammed Ebrahim
Mohammed Ebrahim

Reputation: 869

you can use below query

SELECT id,title,date FROM news 
UNION All
SELECT id,title,date FROM gallery 
ORDER BY date, id, title

Upvotes: 0

John Woo
John Woo

Reputation: 263693

use UNION

SELECT id, title, date FROM news
UNION ALL
SELECT  id, title, date FROM gallery
ORDER BY date, id, title

Upvotes: 4

Mortalus
Mortalus

Reputation: 10712

To achieve this use UNION clause like this ....

SELECT id,title,date FROM news 
UNION
SELECT id,title,date FROM gallery 

Upvotes: 0

Related Questions