3

好的,我今天整天都在为此烦恼,无法让它工作,基本上我试图从一个临时表中随机查询 12 张照片,其中包含所有活跃登录用户尚未投票的照片。

错误显然是#1137 - Can't reboot table: 'r1' which temp table can only be reference一次。

    CREATE TEMPORARY TABLE unvoted_photos
    SELECT *
    FROM photo
    WHERE photo.photo_uid 
    NOT IN 
    ( SELECT photo_uid
    FROM vote
    WHERE vote.user_uid = '12345' ) ;

    SELECT photo_uid, caption, storage_path
      FROM unvoted_photos AS r1 
      JOIN (SELECT (RAND() * 
                    (SELECT MAX(id)
                    FROM unvoted_photos)) AS sid)
                    AS r2
     WHERE r1.id >= r2.id
     ORDER BY r1.id ASC
     LIMIT 12;

由于性能问题,随机选择查询遵循此示例。否则这肯定会奏效。

    SELECT ... FROM photo WHERE photo_uid NOT IN ( voted images subquery ) ORDER BY RAND() LIMIT 12 
4

1 回答 1

0

根据关于该问题的讨论,这是一种将两者合并在一起的方法,您应该可以立即运行。我会用JOINs 重写它,但在这种情况下,我已将临时表放入子查询中,这样您就可以看到发生了什么。

SELECT photo_uid, caption, storage_path
  FROM (
          SELECT photo_uid, caption, storage_path
          FROM photo
          WHERE photo.photo_uid 
          NOT IN 
          ( 
            SELECT photo_uid
            FROM vote
            WHERE vote.user_uid = '12345' 
          )

       ) r1 
  JOIN (SELECT (RAND() * 
                (SELECT MAX(id)
                FROM unvoted_photos)) AS sid)
                AS r2
 WHERE r1.id >= r2.id
 ORDER BY r1.id ASC
 LIMIT 12;
于 2013-02-07T14:58:41.433 回答