如果condition返回true,则插入Multiple value

时间:2013-01-26 06:55:25

标签: mysql case

在表中插入多个值当If条件返回true时。如果condition检查两个表数据并相应地返回true和false。

结构 -

products: id, qty_on_hand
orders: id, product_id, qty ,price,room_number etc
roomTable :id,product_id,room_number,booked_status

当请求的总数量少于qty_on_hand

时,在订单表中插入所有数据

请告诉我们如何使用案例陈述。提前预订

2 个答案:

答案 0 :(得分:1)

INSERT INTO orders (id, product_id, qty ,price,room_number, etc)
SELECT $id, $product_id, $qty, $price, $room_number, ...
FROM products
WHERE id = $id AND $qty < qty_on_hand;

将所有$xxx替换为您要插入的数据。

答案 1 :(得分:0)

我认为上一个查询中的所有内容都是rite,除了“id”部分以及可能缺少的联产 我认为product_id是请求的ID .. 还需要在roomTable上进行内部联接以获取...数据

我的直觉是订单表中的id列是自动生成的

INSERT INTO orders (product_id, qty ,price,room_number, etc)
SELECT products.id, products.qty, products.price, roomTable.room_number, ...
FROM products
Inner join roomTable
on roomtable.product_id = products.id
WHERE products.id = $id AND $qty < qty_on_hand;

我假设代码为::

    begin tran orderstransaction
     //This will insert a new order with an autogenerated order id..    
      INSERT INTO orders (product_id, qty ,price,room_number, etc)
        SELECT products.id, products.qty, products.price, roomTable.room_number, ...
        FROM products
        Inner join roomTable
        on roomtable.product_id = products.id
        WHERE products.id = $id AND $qty < qty_on_hand;

    //this will reduce the qty_on_hand by $qty now that an order has been posted 
    update products set qty_on_hand = (qty_on_hand - $qty)
    where products.id = $id

    commit tran orderstransaction

这是我的编辑,至少有一个可以使用的语句

SQL Insert Statement that worked for me
..................
this sql statement below assumes that id in orders is not autogenerated..
i did not see an attribute for price in products so hardcoded it to 2500 to be replaced with products.price assuming there is a price in products table.
Now assuming that u r querying for product_id=1 and qty=250 which are ur inputs for the query, am inserting order id 10000 into orders
INSERT INTO orders (id,product_id, qty ,price,room_number)
        SELECT 10000,products.id,250 , 2500, roomTable.room_number
        FROM products
        Inner join roomTable
        on roomtable.product_id = products.id
        WHERE products.id = 1 AND 250 < products.qty_on_hand
..........................................................
This Sql assumes order id is autogenerated
  INSERT INTO orders (product_id, qty ,price,room_number)
        SELECT products.id,250 , 2500, roomTable.room_number
        FROM products
        Inner join roomTable
        on roomtable.product_id = products.id
        WHERE products.id = 1 AND 250 < products.qty_on_hand
........................................................