美文网首页
chapter19:插入数据

chapter19:插入数据

作者: WeirdoSu | 来源:发表于2017-12-20 17:20 被阅读0次

    INSERT语句。

    插入完整的行

    INSERT INTO customers
    VALUES(
        'Pep E. LaPew',
        '100 Main Street',
        'Los Angeles',
        'CA',
        '90046',
        'USA',
        NULL,
        NULL);
    

    !:对每个列必须给出一个值,没有值用NULL;各个列必须以他们在表定义中出现的次序填充;但这种语法不安全,太依赖顺序,应避免使用。

    安全方法:

    INSERT INTO customers(cust_name,
        cust_address,
        cust_city,
        cust_state,
        cust_zip,
        cust_country,
        cust_contact,
        cust_email)
    VALUES('Pep E. LaPew',
        '100 Main Street',
        'Los Angeles',
        'CA',
        '90046',
        'USA',
        NULL,
        NULL);
    

    !:

    • 总是使用列的列表。
    • 仔细地给出值。
    • 省略列:该列为NULL;或在表定义中给出默认值。
    • 提高整体性能:LOW_PRIORITY降低INSERT语句的优先级,INSERT LOW_PRIORITY INTO

    插入多个行

    例:

    INSERT INTO customers(cust_name,
        cust_address,
        cust_city,
        cust_state,
        cust_zip,
        cust_country,
        cust_contact,
        cust_email)
    VALUES('Pep E. LaPew',
        '100 Main Street',
        'Los Angeles',
        'CA',
        '90046',
        'USA',
        NULL,
        NULL);
    INSERT INTO customers(cust_name,
        cust_address,
        cust_city,
        cust_state,
        cust_zip,
        cust_country,
        cust_contact,
        cust_email)
    VALUES('M. Martian',
        '42 Galaxy Way',
        'New York',
        'NY',
        '11213',
        'USA');
    

    或者,只要每条INSERT语句中的列名(和次序)相同:

    INSERT INTO customers(cust_name,
        cust_address,
        cust_city,
        cust_state,
        cust_zip,
        cust_country,
        cust_contact,
        cust_email)
    VALUES(
        'Pep E. LaPew',
        '100 Main Street',
        'Los Angeles',
        'CA',
        '90046',
        'USA',
        NULL,
        NULL
    ),
    (
        'M. Martian',
        '42 Galaxy Way',
        'New York',
        'NY',
        '11213',
        'USA'
    );
    

    插入检索出的数据

    例:假如你想从另一表中合并客户列表到你的customers表:

    INSERT INTO customers(
        cust_id,
        cust_contact,
        cust_email,
        cust_name,
        cust_address,
        cust_city,
        cust_state,
        cust_zip,
        cust_country
    )
    SELECT cust_id,
        cust_contact,
        cust_email,
        cust_name,
        cust_address,
        cust_city,
        cust_state,
        cust_zip,
        cust_country
    FROM custnew;
    

    !:实际上列名不一定要一一匹配。

    相关文章

      网友评论

          本文标题:chapter19:插入数据

          本文链接:https://www.haomeiwen.com/subject/ngtnwxtx.html