2

我正在尝试将值直接从一个mysql表复制到另一个......但问题是,有很多行要复制,因此子选择语句将返回很多行但参数:order_id只写一次。

鉴于这个问题,我很难弄清楚如何编写这个过程:

# 1: Create new Order & Copy the cart basket to the Order basket
$order_id = addOrder($customer_id);
if ($order_id > -1) {
    $sql = "INSERT INTO tbl_order_basket(order_id, product_id, product_name,
                                         basket_qty, basket_price, subtotal)
                 VALUES (:order_id, (SELECT (cart.product_id, product.name,
                                     cart.cart_qty, cart.cart_price, cart.subtotal)
                                FROM tbl_shopping_cart AS cart
                          INNER JOIN tbl_product AS product
                                  ON cart.product_id = product.id
                               WHERE cart.php_sesskey = :session_id)
                        )
                  WHERE order_id=:order_id;";
}

这是我要复制的数据:

ORDER BASKET            CART BASKET         PRODUCTS
FK  order_id            FK  php_sesskey
FK  product_id      <-- FK  product_id  === PK  id
    product_name    <--                 <--     name
    basket_qty      <--     cart_qty
    basket_price    <--     cart_price                              # <-- : copy to
    subtotal        <--     subtotal                                # === : join on

我该怎么做呢?

注意:我使用的是 PHP 5 和 MySQL 5.5

4

3 回答 3

4

也许你可以用这个?

INSERT INTO ... SELECT ... FROM ... WHERE ...

要创建查询,首先要创建一个SELECT它,它会为您提供要插入的所有字段。然后前置INSERT INTO <table>,你就完成了。

于 2012-04-23T13:50:18.757 回答
1

查看SELECT INTO TABLE

INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
于 2012-04-23T13:49:58.030 回答
1

尝试使用下面的查询;这种语法过去对我有用。由于WHEREMySQLINSERT语句(手册)中没有,因此我删除了该部分。VALUES另外,在执行INSERT...SELECT手动)时不要使用关键字。

$sql = '
    INSERT INTO tbl_order_basket(order_id, product_id, product_name,
                                     basket_qty, basket_price, subtotal)
      SELECT :order_id, cart.product_id, product.name,
             cart.cart_qty, cart.cart_price, cart.subtotal
      FROM tbl_shopping_cart AS cart
        INNER JOIN tbl_product AS product
        ON cart.product_id = product.id
      WHERE cart.php_sesskey = :session_id)
  ';
于 2012-04-23T14:15:47.673 回答