如何在一个查询中执行插入?

时间:2018-09-28 00:48:28

标签: php mysql database insert

框架:使用XAMPP服务器的本地主机上的MySQL服务器。

我正在尝试将所有这些字段插入特定表“ tbl_labelled_images”:

  1. id_in_raw_image_table
  2. 图片
  3. 标签
  4. 性别

其中的图像来自另一个名为“ tbl_raw_image”的表,而id_in_raw_image_table是表“ tbl_raw_image”中该图像的ID。

然后,标签和性别是用户在运行时使用单选按钮获取的输入。但是问题是我无法在单个查询中插入所有这四个属性。如果所有查询都在同一查询中,则查询只是不会在表中插入任何内容。我尝试了以下查询,但没有一个真正有用:

$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
               (`label`,`gender`,`image`, `id_in_raw_image_table`) '$label','$gender',
               SELECT  image, id FROM raw_images.tbl_raw_image
               WHERE raw_images.tbl_raw_image.id = $id_raw";
$insert_exec = mysqli_query($conn, $query_insert);

$sql = "SELECT * FROM tbl_raw_image WHERE id IN
    (SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query2="INSERT INTO tbl_labelled_image(image, label, id_in_raw_image_table) VALUES('$image','$label','$id'); ";
$rs  = mysqli_query($conn2, $query2);

但是他们都没有为我工作。作为一种变通方法,我目前正在使用复杂的两步插入,如下所示:

$sql = "SELECT * FROM tbl_raw_image WHERE id IN
    (SELECT id FROM (SELECT id FROM tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
$sth = $conn1->query($sql);
$result=mysqli_fetch_array($sth);
$id=$result['id'];
$image=$result['image'];
$label=mysqli_real_escape_string($conn, $_POST["radio"]);
$gender=mysqli_real_escape_string($conn,$_POST["radio-gender"]);
$query_insert="INSERT INTO labelled_images.tbl_labelled_image
               (`image`, `id_in_raw_image_table`)
               SELECT  image, id FROM raw_images.tbl_raw_image
               WHERE raw_images.tbl_raw_image.id = $id_raw;";
$insert_exec = mysqli_query($conn, $query_insert);
$labelled_id=mysqli_insert_id($conn);
$query_label = "UPDATE labelled_images.tbl_labelled_image SET
               `label` = '$label', `gender` = '$gender' WHERE `id`=$labelled_id";
$label_insert_exec = mysqli_query($conn, $query_label);
$query_update_Is_labelled="UPDATE raw_images.tbl_raw_image SET `Is_labelled`= 1 WHERE id= $id_raw; ";
$update=mysqli_query($conn,$query_update_Is_labelled);

它有效,但远非理想。所以我的问题是,有什么方法可以一步执行此插入操作吗?或更一般而言,当要插入的不同记录字段来自不同来源时应该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以尝试在MySQL选择查询SELECT '$label' as label,'$gender' as gender中使用静态值

完整查询:

$query_insert="INSERT INTO labelled_images.tbl_labelled_image
    (`label`,`gender`,`image`, `id_in_raw_image_table`)
        SELECT '$label' as label,'$gender' as gender, image, id FROM raw_images.tbl_raw_image
        WHERE raw_images.tbl_raw_image.id = $id_raw
    ";

已编辑:在 SELECT

之前删除 VALUES()