如何编写mysql语句

时间:2011-06-29 05:07:48

标签: php mysql sql

我做了一个问答游戏系统(mysql + php)。有两个表:

问题表:

qid            question        options      answer  level
23              1+1=?          1^2^3^4        2       1
24             10*10=?       1010^100^1000    100     1 
.....
3212          9999*32342/765   ...           ...      4 (more large the level is more difficult the question is)  

......超过一万条记录......

用户表:

userID       username        used(this field store qid someone has answered that from question table )
1            mary           23,56 (means she had answered qid=23 qid=56 question from question table)
2            mike           1,4,6,2123,567,2341,678,431234,45125
3            jack           3,23,24,.....
...

..很多用户......

当玩家登录并开始玩游戏时,系统会从question表中选择level=1中的4个问题,并选择level=2 ... 4个问题那level=3 .... level=4。根据用户表中的used,所有这些问题都没有被使用过。

如何编写mysql语句?

2 个答案:

答案 0 :(得分:1)

使用您当前的架构,您至少需要两个查询。第一个将used值返回给PHP。然后PHP需要在第二个查询中使用它:

$q   = mysql_query( 'select used from user_table where id=1' ) 
            or die( mysql_error() );
$row = mysql_result_array( $q );
$ids = $row[ 0 ];
$q   = mysql_query( 
    "SELECT * FROM (
       select * from question_table where level = 1 and qid not in ($ids) ORDER BY (RAND()) limit 4
    )
    UNION
    SELECT * FROM (
       select * from question_table where level = 2 and qid not in ($ids) ORDER BY (RAND()) limit 4
    )
    UNION
    SELECT * FROM (
       select * from question_table where level = 3 and qid not in ($ids) ORDER BY (RAND()) limit 4
    )
    UNION
    SELECT * FROM (
       select * from question_table where level = 4 and qid not in ($ids) ORDER BY (RAND()) limit 4
    )" 
) or die(mysql_error());

答案 1 :(得分:0)

最简单(也可能是最有效的方法)是在2个查询中执行此操作。

  1. SELECT used FROM user WHERE userID = 'mike'
  2. SELECT * FROM question WHERE level = 1 qid NOT IN (result from query 1) ORDER BY RAND() LIMIT 4
  3. 然后为每个级别重复查询2.