2017-05-30 17 views
1

私は小さなオンラインストアを作ろうとしています。私は2つのテーブル:cart_productsorder_productsを持っています。これらの表の中には、カートに追加できる2種類の品目:promotionproductsがあります。これらの2つのタイプのアイテムは、promotionsproductsという異なるテーブルに格納されています。あるテーブルから別のテーブルにデータを挿入する -

最初に、ユーザがordersテーブルに転送され、cartテーブルから削除されたことをユーザが確認すると、すべての製品/プロモーションが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です。誰も私がこれについてどうやって行くことができるか知っていますか?どんな助けでも大歓迎です!

答えて

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」の句を忘れてしまったと考えていますjoin

+1

ありがとうございます。ありがとうございました。私は「SELECT」をかっこの中に入れなければなりませんでした。そうでなければエラーになりました。しかし、私はそれを働かせる。 –

+0

私の答えはあなたに受け入れられて良かった@BrianMoreno – AlVaz

関連する問題