代码之家  ›  专栏  ›  技术社区  ›  community wiki Bjorn Tipling

是否可以从我的MySQL数据库中的一个表中的一行中获取值并插入到同一数据库中的另一个表中?

  •  3
  • community wiki Bjorn Tipling  · 技术社区  · 5 年前

    所以说我有一个 products 带有产品列表的表,其中一个字段是 price . 这张桌子还有一个 id 字段。当有人购买时,我会在另一个名为 purchases . 此表还具有一个名为 价格 和A productid 映射到产品表的字段 身份证件 字段。我想知道是否可以从我的products表中获取价格,并将其插入到一个SQL查询中的purchases表中。

    这在MySQL中是可能的吗?

    谢谢!

    3 回复  |  直到 16 年前
        1
  •  10
  •   community wiki chaos    16 年前

    当然。在我通常的做法中,我只是将价格作为插入的一部分发送,但是如果您确实需要从产品表中提取价格,那么您可以使用子选项执行此操作,例如:

    INSERT INTO `purchase`
    SET `product_id` = $whatever,
    `price` = (
        SELECT `price`
        FROM `product`
        WHERE `id` = $whatever
    )
    
        2
  •  5
  •   community wiki Cade Roux    16 年前
    INSERT INTO purchases (
        price
        ,productid
        ,add your other columns here
    )
    SELECT price
        ,id
        ,add your other columns here
    FROM products
    WHERE add your selection criteria here
    
        3
  •  4
  •   community wiki 3 revs Michael Buen    16 年前

    可能的:

    insert into purchases(purchase_id, product_id, price) 
    select 88, product_id, current_price from product 
    where product_id = 'KEYB'
    

    要包括当前折扣:

    insert into purchases(purchase_id, product_id, price, discount) 
    select 88, product_id, current_price, current_discount from product 
    where product_id = 'KEYB'