Select records from one table based on data in a second table
Given the following tables:
Code:
Advertisers
-----------------------------
Company | Expiration_Date
-----------------------------
XYZ Co. | 1356972959
ABC Inc. | 1354291206
-----------------------------
Ads
-------------------------------------------------
Company | URL TEXT
-------------------------------------------------
XYZ Co. | www.example.com Click here
ABC Inc. | www.mysite.com On sale now
XYZ Co. | www.otherexample.com Widgets here
-------------------------------------------------
The idea is to select a single random record from the Ads table for each advertiser whose expiration date is in the future (each advertiser may have several links, but I only want the query to return one for each company). I've tried many things and all seem to bring up a result close to, but not exactly, what I need. The closest I've come is as follows:
SELECT *
FROM Ads
JOIN Advertisers ON Ads.Company = Advertisers.Company
WHERE Advertisers.Expiration_Date < CURTIME( )
That particular query selects some records where the advertiser's expiration date is in the past, and is missing at least one where the expiration date is in the future, so obviously I'm getting something wrong.
Any pointers much appreciated.
Thanks,
Matthew