简体   繁体   中英

MySQL INSERT…SELECT for one column only

I want to insert multiple row in my table, the data for this query is fetched from front end. One column in this query is not passed from front end, its value is determined at query execution time from another table. I can put these array in loop & perform one SELECT query & one INSERT query for each item, but I want to avoid it, thus I created one large INSERT query! Till here everything fine, but now that one value should be from another table!

I can use INSERT...SELECT method https://dev.mysql.com/doc/refman/5.6/en/insert-select.html

It allows insertion of multiple rows, all rows matched are inserted & I can pass a dummy column value in SELECT part to customise the query. But now problem is these ' faked columns ' are same for all rows, they should me in loop, different for each loop! how to achieve that?

Scenario

$products = array(
    "1" => array(
        "product_name" => "apple",
        "units" => "1",
    ),
     "2" => array(
        "product_name" => "mango",
        "units" => "3",
    ),
);

Suppose this is the array I get from front end, each key is product id which contains other description for product in cart. Now I'll insert this in Orders table but price is missing, which I have to fetch from Products table! For which I can perform select using product id.

Similar Question:

This answer uses faked columns:

MYSQL INSERT SELECT problem

Copied from accepted answer:

INSERT INTO website (url,fid) SELECT $site,id FROM users WHERE name = $user

Here $site will be same for all inserted records, I want it different for each record as per my array!

I research on this topic but can't find desired answer :(

Try this code if it helps,

<?php 
$products = array(
  "1" => array(
    "product_name" => "apple",
    "units" => "1",
  ),
  "3" => array(
    "product_name" => "mango",
    "units" => "3",
  ),
  "7" => array(
    "product_name" => "mango",
    "units" => "3",
  ),
);


$result = $conn->query("SELECT product_id, product_price FROM product_table WHERE product_id IN (".implode(',', array_keys($products)).")");
while($row = $result->fetch_assoc()) {
  $prod_price[$row['product_id']] = $row['product_price'];
}

$qry = array();
foreach ($products as $key => $value) {
   $qry[] = "('".$value['product_name']."', '".$value['units']."', '".$prod_price[ $key]."')";
}

$insert = "INSERT INTO orders (`product_name`, `units`, `product_price`) VALUES ".implode(', ', $qry);

I come up with this code based on my understanding of your question. Let me know if it works.

This approach just hits the DB twice only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM