我有4张桌子,照片,标签,photos_tags和访问。
我必须选择前30张照片,这些照片应按照访问表中系数总和获得的因子排序。
我正在尝试此查询,但它没有说“每个派生表必须有一个别名”
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()
编辑:查询我正在尝试抛出#1064 - 您的SQL语法出错了;检查与MySQL服务器版本对应的手册,以便在''附近使用正确的语法.AS Table2 ORDER BY计算LIMIT 30 )如表3第10行的ORDER BY RAND()'
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 查询引发#1054 - 'where子句'中的未知列'Photo.id'
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()
答案 0 :(得分:1)
我认为这是您想要的查询:
SELECT *
FROM (SELECT p.*, computed
FROM Photos AS p
LEFT JOIN (SELECT pt.photo_id, SUM(count) total
FROM photos_tags pt
JOIN visits v
ON v.tag_id = pt.tag_id
GROUP BY photo_id) AS pt
ON p.id = pt.photo_id
where p.id NOT IN ( )
ORDER BY computed
LIMIT 30) AS t1
ORDER BY RAND()