简体   繁体   中英

Inserting data into temporary mysql table with case

Consider the following example table:

CREATE TABLE items
    (`id` int, `productName` varchar(7), `price_new` decimal(10,2), `price_used` varchar(55))
;

INSERT INTO items
    (`id`, `productName`, `price_new`, `price_used`)
VALUES
    (1, 'cup', 10.50, 5.50),
    (2, 'plate', 9.50, 4.50),
    (3, 'mug', 8.50, 3.50)
;

For an application I wish to create a temporary table based on what the user has. The user would have say a 'cup' with condition of 'new'. (stored in a php array)

My desired temporary table would be something like:

CREATE TEMPORARY TABLE IF NOT EXISTS tempTable (
         `id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
          `name` varchar(7) NULL,
          `itemCondition` varchar(7) NULL,
          `price` decimal(10,2) NULL
        );

My question is this: If I create this temporary table how could I insert 'cup' and 'new' with MySQL selecting the price from the items table based on the itemCondition? psuedocode:

Insert: 
(1, 'cup', (
    if itemCondition == 'new' 
    (select Items.price_new where items.productName = 'cup')
    ELSE 
    (select Items.price_used where items.productName = 'cup') 

Thank you for your assistance.

The problem is that until you insert the data into the temptable, sql will not know the value of the imtemCondition field. The value 'new' is supplied in the insert statement itself as a fixed value.

You will need either stored procedure that selects the price based on a parameter value and then insert that price into the temporary table, or you can implement the same logic using php.

Steps:

  1. Provide user id, name, and item condition.
  2. Select the price based on the item condition.
  3. Insert all data to the temporary table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM