I am using
SELECT *
FROM picture
INNER JOIN user ON picture.fbid = user.fbid
WHERE hide = 0
AND userhide = 0
ORDER BY gender, RAND( ) LIMIT 0 , 1
This executes and gives me the link to a picture of a random row where the gender is female. It takes around 15 seconds to execute.
How could I change the SQL so that it is calculated fast? Should I add a gender column in the Picture table so that it doesn’t combine both the table and then gets a random row or is there some other way to optimise the SQL?
[EDIT] You can do the same with a MySQL stored procedure, I just coded it here: http://sqlfiddle.com/#!2/d0e6a/2
(Note: Not having the count done in every query would aliviate the load, otherwise in this particular case it can be even slower and I would recommend to keep your query, but with index optimization. Or check this out: Is cross-table indexing possible?)
[EDIT 2] Here’s another example with index optimization using an average of 50000 random entries in each table: http://sqlfiddle.com/#!2/bfbe1/1 The query takes less than 100ms (Without indexes I left it running for several minutes and still no result!). You can create indexes on existing tables using CREATE INDEX
Here’s my solution using 2 queries from a PHP script:
This should make you query a lot faster.
Also, if your tables are big (which I guess it’s the case, since the query takes 15 secs) it would help if the conditional/join fields are indexed.