mySQL:向自动选择查询分配自动增量ID号

时间:2018-12-07 04:21:30

标签: php mysql phpmyadmin

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

1 个答案:

答案 0 :(得分:2)

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