坚持写首页推荐

SQL—插入数据

2016-10-19  本文已影响119人  Mg明明就是你

数据插入(INSERT)

1、插入完整的行

INSERT INTO Customers VALUES ('0343454',
                              'toy land',
                              '435 Any Street',
                              'New York',
                              'NY',
                              '3333',
                              'USA',
                              NULL,
                              NULL);
// Tip:虽然这种写法很简单,但是并不安全,应尽量避免使用


/* 建议还是使用以下写法比较安全:
   因为提供看列名,VALUES必须以其指定的次序匹配指定的列名,不一定按各列出现在表中的实际次序。
   优点在于:即使表的结构改变,这条INSERT语句仍然能够正确工作。*/
INSERT INTO Customers (cust_id,
                       cust_name,
                       cust_address,
                       cust_city,
                       cust_state,
                       cust_zip,
                       cust_country,
                       cust_contact,
                       cust_email)
             VALUES   ('0343454',
                       'toy land',
                       '435 Any Street',
                       'New York',
                       'NY',
                       '3333',
                       'USA',
                       NULL,
                       NULL);

2、插入行的一部分

INSERT INTO Customers (cust_id,
                       cust_name,
                       cust_address,
                       cust_city,
                       cust_state,
                       cust_zip,
                       cust_country)
             VALUES   ('0343454',
                       'toy land',
                       '435 Any Street',
                       'New York',
                       'NY',
                       '3333',
                       'USA',);
/*
  没有给出cust_contact和cust_email这两列提供的值。这表示没必要在INSERT语句中包含它们。
*/
注意:省略列
注意:省略所需的值

3、插入某些查询的结果;

INSERT INTO Customers (cust_id,
                       cust_name,
                       cust_address,
                       cust_city,
                       cust_state,
                       cust_zip,
                       cust_country)
               SELECT cust_id,
                       cust_name,
                       cust_address,
                       cust_city,
                       cust_state,
                       cust_zip,
                       cust_country
            FROM CustNew;
// 说明:将从CustNew表中查询到的数据插入Customers 表中



从一个表复制到另外一个表(SELECT INTO)

    `SELECT * INTO CustCopy FROM Customers`
/* 说明:
     1、 这条SELECT 语句创建一个名为CustCopy的新表,并把Customers表的整个内容复制新表中
     2、要想只复制部分的列,可以明确给出列名,而不是使用*通配符。
*/

#### 而MariaDB、MySQL、Oracle、PostgreSQL和SQL使用的语法不一样
    `CREAT  TABLE CustCopy  AS SELECT * FROM Customers`
上一篇 下一篇

猜你喜欢

热点阅读