0

当 If 条件返回 true 时,在表中插入多个值。if 条件检查两个表数据并相应地返回 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 时,在订单表中插入所有数据

请告知如何在此中使用 case 语句。提前谢谢

4

2 回答 2

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为您要插入的数据。

于 2013-01-26T07:22:21.510 回答
0

我认为上一个查询中的所有内容都是常规的,除了“id”部分和 roomtable 上可能缺少的连接我认为 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
........................................................
于 2013-01-26T08:38:22.283 回答