Why do i get this error with this query?
SELECT distinct fileID
FROM ( SELECT fileID from file order by fileID desc limit 30) as R1
UNION (SELECT fileID from visit order by counter desc limit 30 )
WHERE status = 1 order by rand() LIMIT 10
error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ‘WHERE status = 1 order by rand() LIMIT 10’ at line 1
what i want is to select the top 30 most viewed file and top 30 most recent file and then randomly select from them limit by 10 with the file status = 1.
put your two queries for newest files and most visits in a UNION inside a subquery, and then reorder the resulting derived table by RAND and limit the result to 10.
Note:
you state you want to select recently visited files.. but ordering by “counter” in fact selects the files with the most visits .. not the recent ones.
As a reaction to the OPs comment, i added a JOIN in one of the selects to check if the file related to a visit has status = 1.
Also Note:
for this query to perform fast on larger amounts of data you should add index on the fields
file.statusandvisit.counter. IffileIDis not already a key / index for those tables, you should add an index on this field too.The
visit.file_idis notUNIQUEso the above query may have the same file_ids in the sub-result of the 2nd subquery (the duplicates will be removed by the finalDISTINCTbut that means that the secondLIMIT 30does not work as wanted). Possible correction: