0

我有 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 服务器版本相对应的手册,以在第 10 行的 ') AS Table2 ORDER BY computed LIMIT 30 ) AS Table3 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()
4

1 回答 1

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()
于 2013-07-27T00:47:29.147 回答