我怎么能简化这个mysql语句?

时间:2011-06-28 17:28:53

标签: mysql sql

我使用follow mysql语句通过php从mysql获取一些信息。

( SELECT * 
    FROM mytable 
   WHERE qid NOT IN ({$used['used']}) 
     AND level = 1 
ORDER BY RAND() 
   LIMIT 5) 
UNION 
( SELECT * 
    FROM app_mytable _qt 
   WHERE qid NOT IN ({$used['used']}) 
     AND level = 2 
ORDER BY RAND() 
   LIMIT 5) 
UNION 
( SELECT * 
    FROM app_mytable _qt 
   WHERE qid NOT IN ({$used['used']}) 
     AND level = 3 
ORDER BY RAND() 
   LIMIT 5) 
UNION 
( SELECT * 
    FROM app_mytable _qt 
   WHERE qid NOT IN ({$used['used']}) 
     AND level = 4 
ORDER BY RAND() 
   LIMIT 5)

$used['used']是一套qid,喜欢23,31,653,147,146,134,6 ......

我怎样才能简化这个mysql语句?

2 个答案:

答案 0 :(得分:1)

您可以使用用户变量按组继续运行总计。这是未经测试的,但以下内容应该有效:

select *, 
       @running:=@previous:=NULL
  from (
         select *,
                @running:=if(@previous=inside.level,@running,0)+1 as TOTAL,
                @previous:=inside.level
           from (
                  select * 
                    from mytable
                   where qid NOT IN ({$used['used']})
                   order by level, rand() 
                ) as inside
       )as outside
 where TOTAL < 5;

答案 1 :(得分:0)

一些动态的sql可以消除你的复制粘贴...这样你就可以轻松地将它扩展到你想要的多个级别,只需修改max_level。

DECLARE current_level INT;  SET current_level = 1;
DECLARE max_level INT; SET max_level = 4;
DECLARE full_sql VARCHAR(1000); SET full_sql = '';
DECLARE base_sql VARCHAR(1000); SET base_sql = '(SELECT * FROM mytable WHERE qid NOT IN ({$used['used']}) AND level = ? ORDER BY RAND() limit 5) ';

WHILE current_level <= max_level
    SET full_sql = CONCAT(full_sql, REPLACE(base_sql, '?', current_level));

    IF current_level < max_level THEN
      SET full_sql = CONCAT(full_sql, ' UNION ');
    END IF
    SET current_level = current_level + 1;
END WHILE

PREPARE s1 FROM full_sql;
EXECUTE s1;
DEALLOCATE PREPARE s1;