从评论部分的情况来看,您要问的是您希望有一个更优化的查询过程。现在您正在使用两个不同的查询来填充您的两个表,并且您想知道是否可以更优化地完成。
首先,不可能用 ONE 查询填充 两个 不同的表。
但是,您可以做的是使用事务。
此答案的其余部分将假设您使用 PHP 作为后端脚本语言(如您自己标记的那样)。
此外,您是否在查询中使用准备好的语句本身并不明显。如果您不这样做,我强烈建议您使用准备好的语句。否则,您将面临 SQL 注入(SQLI 攻击)。
我将继续在此答案中使用 mysqli 准备好的语句。
<?php
// Your input post variables
$name = $_POST['name'];
$foodArray = $_POST['foodArray'];
/*
I'm using a function to handle my queries,
simply because it makes large piles of code easier to read.
I now know that every time the function:
createUserAndFood($name, $foodArray);
is called, that it will populate my user and food table.
That way I don't have to worry about writing all the code multiple times.
*/
function createUserAndFood($name, $foodArray){
// food array values
$foodValues = array_values($foodArray);
// DB variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
/*
Stops the query from auto commiting,
I'll explain later, you can "maybe" disregard this.
*/
$conn->autocommit(FALSE);
// Declare the query
$sql = "INSERT INTO userTable(name) VALUES(?)";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $name);
// Execute the query
$stmt->execute();
// Fetch last inserted id
$lastID = $conn->insert_id;
$sql = "INSERT INTO foodTable(userId, food) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
for($i = 0; $length = count($foodValues) > $i; $i++){
$stmt->bind_param("is", $lastID, $food);
$food = $foodValues[$i];
$stmt->execute();
}
// Commits the query / queries
$conn->commit();
// Close connection
$stmt->close();
$conn->close();
}
?>
由于您想优化查询,我们在这里使用的一般想法是,我们通过 PHP 使用 MySQL 函数 LAST_INSERT_ID(); 并将其存储到变量中。
现在,如果您使用自动递增的 id,这主要是相关的。如果你不是,你可以忽略这个特定的逻辑并使用其他东西。但如果你是,请继续阅读。
我们将最后一个 id 存储到变量中的原因是因为我们需要多次使用它(新用户可能有不止一种喜欢的食物)。如果您不将最后一个 id 存储到变量中,它将取而代之的是在初始插入后第二个表的自动递增值,这意味着在您的第三个插入语句和转发时,您将使用错误的 id。
现在,正如我承诺解释的那样,我使用$conn->autocommit(FALSE); 和$conn->commit(); 的原因是因为您可能不希望数据库中的数据集不完整。想象一下用户输入正在发生,但您的数据库在这一切中崩溃了。您将拥有不完整的数据集。如果这不是您真正关心的问题,那么您可以忽略它。
为了简化 MySQL 方面发生的事情,可以这样考虑:
BEGIN;
INSERT userTable SET name = '$name';
SET @lastID = LAST_INSERT_ID();
INSERT foodTable SET id = @lastID, food = '$food';
COMMIT;