Py学习  »  DATABASE

mysql:为double-select查询分配自动增量id号

Atheya • 5 年前 • 1563 次点击  

我正在创建一个程序,其中我从一个表中选择的数据被随机分组。每个组的注册ID号保存到另一个表中(作为外键),并且每个组成员都被分配了一个组ID,该组ID随着创建的每个新组而自动递增。

$GroupSize = $_POST['groupsize'];

//Connect to the Server+Select DB
$con = mysqli_connect($host, $user, $password, $dbName) or die("Nope");

if (isset($_POST['create'])) {

//assign group id to groups created
//insert groupinformation to table from userInformation
      $query = "SELECT  RegistrationId FROM (Select * from userInformation order by RAND() LIMIT ".$GroupSize.") INTO groupInformation";
      $result = mysqli_query($con, $query) or die ("query failed" . mysqli_error($con));


//display group and information
    echo "<table border='1' >";
    echo "<tr><th>RegId</th><th>Name</th><th>Address</th><th>Email</th></tr>";
    while (($row = mysqli_fetch_row($result)) == true) {
        echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
    }
    echo "</table>";

//if group is less than 2 create error message

}

mysqli_close($con);

我的问题是,我无法将groupid分配给提取的结果,因为无法复制自动递增的数字。这是我的错误:

query failed Every derived table must have its own alias

这是我的表模式

Table schemas user

Table schemas group

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43302
 
1563 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Strawberryshrub Eve 晨曦
Reply   •   1 楼
Strawberryshrub Eve 晨曦    6 年前

GroupId 自动递增,然后再创建一列 RandomGroupId 在里面 groupInformation ,然后粘贴查询:

INSERT INTO groupInformation(RandomGroupId,RegistrationId) 
SELECT randomRegistrationId,RegistrationId 
FROM (Select *,RAND() AS randomRegistrationId 
      FROM userInformation ORDER BY randomRegistrationId LIMIT ".$GroupSize."
      ) AS j