mysql:为一个double-select查询分配一个自动递增的id号

nbnkbykc  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(281)

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

$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

这是我的表格

blpfk2vs

blpfk2vs1#

GroupId 自动递增,然后再创建一列 RandomGroupIdgroupInformation ,然后粘贴查询:

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

相关问题