Snatch
Snatch

Reputation: 27

Order multiple tables in MySql

i have this

ads

ad_id   ad_path     ad_explain      date    
1       1.jpg       something       2012 03:35:10 PM
2       2.jpg       something       2012 03:05:27 PM


books

book_id       book_name     date
1             first         2012 03:45:27 PM
2             second        2012 03:10:27 PM

and i want the get all the data from these two tables and order them by date like :

book_id       book_name     ad_id    ad_path      ad_explain      date
                             2        2.jpg       something       2012 03:05:27 PM
2             second                                              2012 03:10:27 PM
                             1        1.jpg       something       2012 03:35:10 PM
1             first                                               2012 03:45:27 PM

Upvotes: 1

Views: 87

Answers (2)

Filipe Silva
Filipe Silva

Reputation: 21657

You can do that with UNION:

SELECT book_id, book_name, null as ad_id, null as ad_path, null as ad_explain, date
FROM books
UNION
SELECT null, null, ad_id, ad_path, ad_explain, date
FROM ads
ORDER BY date

See this fiddle for working example

Upvotes: 2

Collin Grady
Collin Grady

Reputation: 2253

You're going to want SQL Joins, but you need columns in common to join on.

books and request_books could be joined on book_id, but ads doesn't seem to have a common column with anything (except date, but that seems an unlikely target), so you'd not be able to bring that in easily.

What is your purpose in wanting all three tables mixed together, when it seems like ads doesn't fit the group?

Upvotes: 0

Related Questions