I have 4 tables, photos, tags, photos_tags and visits.
I have to select the first 30 photos ordered by a factor that should be obtained by the sum of the coefficent in the visits table.
I'm trying this query, but it fails saying "every derivated table must have an alias"
SELECT * FROM (
SELECT *, (SELECT SUM(count) FROM (SELECT * FROM visits AS Visits WHERE Visits.tag_id IN (
SELECT tag_id FROM photos_tags AS PhotosTags WHERE PhotosTags.photo_id = Photo.id
)))
) AS computed FROM photos AS Photo WHERE Photo.id NOT IN (
) ORDER BY computed LIMIT 30
) ORDER BY RAND()
EDIT: Query I am trying that throws #1064 - 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 ') AS Table2 ORDER BY computed LIMIT 30 ) AS Table3 ORDER BY RAND()' at line 10
SELECT * FROM (
SELECT *, (
SELECT SUM(Table1.count) FROM (
SELECT * FROM visits AS Visits WHERE Visits.tag_id IN (
SELECT tag_id FROM photos_tags AS PhotosTags WHERE PhotosTags.photo_id = Photo.id
)
) AS Table1
) AS computed FROM photos AS Photo WHERE Photo.id NOT IN (
) AS Table2 ORDER BY computed LIMIT 30
) AS Table3 ORDER BY RAND()
EDIT2 Query that throws #1054 - Unknown column 'Photo.id' in 'where clause'
SELECT * FROM (
SELECT *, (
SELECT SUM(Table1.count) FROM (
SELECT * FROM visits AS Visits WHERE Visits.tag_id IN (
SELECT tag_id FROM photos_tags AS PhotosTags WHERE PhotosTags.photo_id = Photo.id
)
) AS Table1
) AS computed FROM photos AS Photo WHERE photos.id NOT IN (
1,2
) ORDER BY computed LIMIT 30
) AS Table3 ORDER BY RAND()