我正在尝试将值直接从一个mysql表复制到另一个...但问题是,要复制的行数很多,因此sub-select语句将返回很多行但是param :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
答案 0 :(得分:4)
也许你可以使用这个?
INSERT INTO ... SELECT ... FROM ... WHERE ...
要创建查询,请先创建一个SELECT
,它会为您提供要插入的所有字段。然后在INSERT INTO <table>
前加上你就完成了。
答案 1 :(得分:1)
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
答案 2 :(得分:1)
尝试使用以下查询;这种语法过去对我有用。由于MySQL WHERE
语句(manual)中没有INSERT
,因此我删除了该部分。另外,在执行VALUES
(manual)时请勿使用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)
';