【问题标题】:Is it possible to take a value from a row in one table in my MySQL database and insert into another table in the same database?是否可以从我的 MySQL 数据库中的一个表中的一行中获取一个值并插入到同一数据库中的另一个表中?
【发布时间】:2009-01-19 03:14:31
【问题描述】:

假设我有一个包含产品列表的products 表,其中一个字段是price。该表还有一个id 字段。当有人购买时,我在另一个名为purchases 的表中插入一行。该表还有一个名为price 的字段和一个映射到产品表id 字段的productid 字段。我想知道我是否可以在一个 SQL 查询中从我的 products 表中获取价格并将其插入到 purchase 表中。

这在 MySQL 中可行吗?

谢谢!

【问题讨论】:

    标签: sql mysql


    【解决方案1】:

    当然。在我的正常实践中,我只是将价格作为插入的一部分发送,但如果您确实需要在此时从产品表中提取价格,您可以使用子选择来完成,例如:

    INSERT INTO `purchase`
    SET `product_id` = $whatever,
    `price` = (
        SELECT `price`
        FROM `product`
        WHERE `id` = $whatever
    )
    

    【讨论】:

      【解决方案2】:
      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】:

        可能:

        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'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-10
          • 1970-01-01
          • 2016-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多