所以我试图建立一个小型网上商店。我有2个表:cart_products
和order_products
。在这些表格中,有两种类型的商品可以添加到购物车中:promotion
和products
。这两种类型的项目存储在名为promotions
和products
的不同表中。
最初,所有产品/促销都会添加到cart
表中,一旦用户签出,它们就会转移到orders
表并从cart
表中删除。
如果所选项目是产品,则promotion_id
值默认设置为0
。如果所选项目是促销,则反之亦然。这是我的基本结构:
cart_products
----------------------------------------------------------------------------------
| cart_products_id | cart_id | product_id | promotion_id | quantity |
----------------------------------------------------------------------------------
| 6 | 1 | 5 | 0 | 2
---------------------------------------------------------------------------------
order_products
----------------------------------------------------------------------------------
| order_id | user_id | product_id | promotion_id | price | quantity |
----------------------------------------------------------------------------------
我遇到的问题是尝试LEFT JOIN
产品/促销活动以获取所选商品的price
。这是我目前的询问。
INSERT INTO order_details (order_id, user_id, product_id, promotion_id, price, quantity)
VALUES(
'6',
'7',
(SELECT
cart_products.product_id,
cart_products.promotion_id,
IF(cart_products.promotion_id = '0', products.price, promotions.price),
cart_products.quantity
FROM cart_products
LEFT JOIN products
ON cart_products.product_id = products.product_id
LEFT JOIN promotions
cart_products.promotion_id = promotions.promotion_id
WHERE cart_products.cart_id = '6')
)
然而,这给了我一个错误Not unique table/alias
。有谁知道我怎么能这样做?非常感谢任何帮助!
答案 0 :(得分:3)
您可以简单地选择常量,以便您可以使用INSERT INTO SELECT语法,而不是像您一样定义值:
INSERT INTO order_details (order_id, user_id, product_id, promotion_id, price, quantity)
SELECT (
'6',
'7',
cart_products.product_id,
cart_products.promotion_id,
IF(cart_products.promotion_id = '0', products.price, promotions.price),
cart_products.quantity
FROM cart_products
LEFT JOIN products
ON cart_products.product_id = products.product_id
LEFT JOIN promotions
ON cart_products.promotion_id = promotions.promotion_id
WHERE cart_products.cart_id = '6'
)
另外,我相信你在第二次左连接中忘记了“ON”条款