简体   繁体   English

如何编写 mysql 语句

[英]how to write mysql statement

I made a quiz game system (mysql+php).there are two tables:我做了一个问答游戏系统(mysql+php)。有两个表:

question table:问题表:

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)  

...more that ten thousand records... ...超过一万条记录...

user table:用户表:

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,.....
...

..many users.... ..许多用户....

When a player logs in and starts to play the game, the system would select 4 questions from the question table that are level=1 and 4 question that level=2 ...4 question that level=3 .... level=4 .当玩家登录并开始玩游戏时,系统会 select question表中的 4 个问题level=1和 4 question that level=2 ...4 question that level=3 .... level=4 . All these question had not be used before according to the used from user table.根据用户表中的used ,所有这些问题以前都没有使用过。

how to write the mysql statement? mysql语句怎么写?

With your current schema, you will need at least two queries.使用您当前的模式,您将需要至少两个查询。 The first will return the used value to PHP.第一个会将used的值返回给 PHP。 PHP will then need to use it in a second query: 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());

The easiest (and probably most efficient way) is to do it in 2 queries.最简单(可能也是最有效的方法)是在 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

Then repeat query 2 for each level.然后对每个级别重复查询 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM