sql—使用insert into插入多个具有不同表头的值的行

oprakyz7  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(342)

我不知道问这个问题是不是很奇怪,但我遇到了这个问题,我试着去解决。我试图在网上冲浪的任何例子(没有找到任何),因此导致我问在这个论坛。
所以问题是:
我有一个如下所示的sql表:

CREATE TABLE product 
(
    productName VARCHAR(100) PRIMARY KEY NOT NULL,
    productDescription VARCHAR(1000) NOT NULL,
    "weight" INTEGER NULL,
    volume INTEGER NULL,
    sizeInformation VARCHAR(1000) NULL,
    brandName VARCHAR(100) NOT NULL,
    FOREIGN KEY (brandName) REFERENCES brand(brandName)
);

我有一个 INSERT 语句如下所示:

BEGIN TRANSACTION;
    INSERT INTO product 
    VALUES ("Power Gel Laundry Detergent - Anti-Bacterial", "Anti-Bacterial", 10, "Dynamo"),
           ("Power Gel Laundry Detergent - Anti-Bacterial", "Anti-Bacterial", 15, "CloroxLOL");
    COMMIT;

所以第一次 INSERT VALUES 语句(其中有数字10),我想把数字10放入 product(weight) ,第二次 INSERT VALUES 语句(有数字15),我想把数字15放进 product(volume) .
有什么办法吗?

lyfkaqu1

lyfkaqu11#

我想你想要:

insert into product (productName, productDescription, weight, volume, brandName)
values 
    ('Power Gel Laundry Detergent - Anti-Bacterial', 'Anti-Bacterial', 10, null, 'Dynamo'),
    ('Power Gel Laundry Detergent - Anti-Bacterial', 'Anti-Bacterial', null, 15, 'CloroxLOL');

其思想是在目标列表中同时包含这两列,并使用 null 价值观。
你也可以有两个独立的 inserts 语句,具有不同的目标列列表(尽管键入的时间较长):

insert into product (productName, productDescription, weight, brandName)
values ('Power Gel Laundry Detergent - Anti-Bacterial', 'Anti-Bacterial', 10, null, 'Dynamo');

insert into product (productName, productDescription, volume, brandName)
values ('Power Gel Laundry Detergent - Anti-Bacterial', 'Anti-Bacterial', null, 15, 'CloroxLOL');

笔记:
始终枚举 insert 语句-如果没有目标列表,数据库希望您为所有列提供值;原始查询已经无效(有4个值,而表有6列)
对文本字符串使用单引号,而不是双引号(尽管有些数据库支持双字符串)-这是所有数据库都支持的sql标准
在定义数据库对象(表、列)时避免使用双引号:它们使事情变得更复杂,通常没有任何好处

相关问题