简体   繁体   English

MySQL CASE的INSERT INTO SELECT语句

[英]Mysql INSERT INTO SELECT statement with CASE

I am currently trying to insert multiple rows (three) of data into my database using one INSERT statement? 我目前正在尝试使用一条INSERT语句将多行(三)数据插入数据库?

INSERT INTO dvd_price
( SELECT
, (SELECT max(dvd_price_id) + 1 FROM dvd_price) --dvd_price_id
, d.dvd_id                                      --dvd_id
, 2                                             --rental amount
, '1-day'                                       --time rented for
FROM dvd d);

The above will insert it once for 1-day ; 上面会插入1-day ; I'd like to have the same statement also insert the data for 2-day and 3-day , with corresponding values ( 2 incremented once for each subsequent insert) for the rental amount. 我想使用相同的语句还插入2-day 3-day的数据,并使用相应的值(对于每个租金,其对应值(每个后续插入将2递增一次))。

To begin with, you should not be attempting to retrieve the next insert id by calling MAX(dvd_price_id) + 1 . 首先,您应该尝试通过调用MAX(dvd_price_id) + 1来检索下一个插入ID。 That is not immune to race conditions, and can potentially cause problems as it is not reliable. 这不能不受比赛条件的影响,并且由于不可靠而可能引起问题。 If you do not have an AUTO_INCREMENT on dvd_price_id already, you are advised to add one and let the RDBMS handle the increment for you. 如果在dvd_price_id上还没有AUTO_INCREMENT ,建议您添加一个,并让RDBMS为您处理增量。

ALTER TABLE dvd_price MODIFY dvd_price_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT;

Now, you don't need to worry about the dvd_price_id at all in the INSERT . 现在,您完全不必担心INSERTdvd_price_id To get all three values for 1-day, 2-day, 3-day you may create a cartesian product by joining against a list of those static values. 要获得1-day, 2-day, 3-day所有三个值,可以通过加入这些静态值的列表来创建笛卡尔积。 That will result in one each of the day values for every row currently in the table. 这将导致表中当前每一行的每一天的值。

INSERT INTO dvd_price (dvd_id, rental_amount, time_rented_for)
  SELECT
    dvd_id,
    2 AS rental_amount,
    rental_period
  FROM
    dvd
    /* join a subquery which creates a list of 'N-day' strings using
       SELECT 'value' UNION SELECT 'value'.....
       With no ON clause, it will do this for every row in `dvd`
     */
    CROSS JOIN (
      SELECT '1-day' AS rental_period 
      UNION SELECT '2-day' AS rental_period
      UNION SELECT '3-day' AS rental_period
  ) rental_periods

Test this first using only the SELECT portion of the query, without the INSERT . 首先仅使用查询的SELECT部分而不使用INSERT

Here is a demonstration of how it works: http://sqlfiddle.com/#!2/a0862/1 这是其工作方式的演示: http : //sqlfiddle.com/#!2/a0862/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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