Forum Moderators: open

Message Too Old, No Replies

PHP and MySQL

My SELECT query is killing me!

         

inveni0

12:31 am on Jan 4, 2009 (gmt 0)

10+ Year Member



Can someone help me make this faster? I'm unfamiliar with subqueries, and the examples I've seen are confusing me for getting this particular function to work:

SELECT * FROM `_ads` JOIN `_images` ON _ads.adId = _images.adId JOIN `_zipcodes` ON _ads.zipcodeId = _zipcodes.zipcodeId ORDER BY RAND() LIMIT 0,4

My problem is that I have thousands of records in the _ads table, and over 30,000 entries in the _zipcodes table. So, this query is joining every ad to zip codes, when I really only need it to join the 4 I'm limiting the query to.

How can I do this?

Thanks!

coopster

10:42 pm on Jan 4, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



SELECT * FROM `_ads` INNER JOIN `_images` ON (_ads.adId = _images.adId) INNER JOIN (SELECT _zipcodes.zipcodeId FROM `_zipcodes` ORDER BY RAND() LIMIT 0, 4) AS randomZips ON (_ads.zipcodeId = randomZips.zipcodeId);

That's how to format the subquery. Untested, you may have to tweak this ...