我正在尝试生成一个随机的4位数字,该数字不在数据库的mysql表中。我用过这个:
$res = mysqli_query($conn, "SELECT FLOOR(RAND() * 9999) AS random FROM table WHERE 'random' NOT IN (SELECT v_code FROM table) LIMIT 1");
if($res->num_rows>0){
while($row = $res->fetch_assoc()){
echo $row['random'];
}
}
这很好,并生成唯一的随机数,但我表格中v_code列的值采用以下格式:20171234。它有 2017 作为前缀。我的问题是如何搜索该格式的随机数?另外,我希望这个随机数有前导零。例如0123,0321,0432等 要搜索的最终号码采用以下格式:例如 2017 0123或 2017 1234,因为这是数据库表中v_code列的格式。请帮帮我。谢谢。
答案 0 :(得分:0)
你可以用NOT LIKE IN
来做$res = mysqli_query($conn, "SELECT FLOOR(RAND() * 9999) AS random FROM table WHERE 'random' NOT LIKE IN (SELECT v_code & '%' FROM table) LIMIT 1");
if($res->num_rows>0){
while($row = $res->fetch_assoc()){
echo $row['random'];
}
}
或REGEXP可能更有效
$res = mysqli_query($conn, "SELECT FLOOR(RAND() * 9999) AS random FROM table WHERE 'random' REGEXP (SELECT v_code & '%' FROM table) LIMIT 1");