首页 文章

mySQL:为双选查询分配自动增量ID号

提问于
浏览
0

我正在创建一个程序,我从一个表中选择的数据被随机分组 . 每个组中的RegistrationID号被保存到另一个表中(作为外键),并为每个组成员分配一个groupID,该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

1 回答

  • 2

    GroupId 自动增量,然后在 groupInformation 中再创建一个 RandomGroupId 列,然后粘贴查询:

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

相关问题