If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Querying multiple tables

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 10-20-05, 18:05
Etruscan Etruscan is offline
Registered User
 
Join Date: Oct 2005
Posts: 3
Querying multiple tables

This seems simple, but I've been stymied for a couple days. I have three
tables with news articles. The tables themselves are structured identically.
Each article in these tables has a date.

I want to pull the 10 latest items (by date) from the 3 tables. I only want
10 items, and I want the latest ones (regardless of which table they came
from).

SELECT * FROM table1, table2, table3 ORDER BY date ASC LIMIT 10

...but that query doesn't work.

Is there another way I can do it... or will I need to resort to pulling the
10 latest from each of the 3 tables and then comparing them in PHP?
Reply With Quote
  #2 (permalink)  
Old 10-20-05, 20:37
popskie popskie is offline
Registered User
 
Join Date: Oct 2004
Location: In cousin's house
Posts: 303
I never try this in mysql but in ms sql u can use union eg.
select * from table1 union
select * from table2 union
select * from table3 limit 10

take note : u should have the same fields in ur tables.
Reply With Quote
  #3 (permalink)  
Old 10-20-05, 22:30
Etruscan Etruscan is offline
Registered User
 
Join Date: Oct 2005
Posts: 3
Quote:
Originally Posted by popskie
I never try this in mysql but in ms sql u can use union eg.
select * from table1 union
select * from table2 union
select * from table3 limit 10

take note : u should have the same fields in ur tables.
Hmmm... do you know where would the ORDER BY directive fit in?
Reply With Quote
  #4 (permalink)  
Old 10-20-05, 22:40
Etruscan Etruscan is offline
Registered User
 
Join Date: Oct 2005
Posts: 3
Ah... got it.

select * from table1 union
select * from table2 union
select * from table3
order by date desc limit 10

...perfect. Thanks so much!
Reply With Quote
  #5 (permalink)  
Old 10-20-05, 22:41
popskie popskie is offline
Registered User
 
Join Date: Oct 2004
Location: In cousin's house
Posts: 303
select * from table1 union
select * from table2 union
select * from table3 order by fieldname asc limit 10

Ok i mention earlier that i never use this in mysql only the union fucntion. Sory for not mentioning that one.
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On