1. 程式人生 > >資料庫建立表以及增刪改查

資料庫建立表以及增刪改查

建立資料庫

         語法:create database [資料庫名]

         例:create database School;

建立表

語法:create table [表名]

        (

            列名1 資料型別,

            列名2 資料型別,

             ……

          )

         例:create table Students (                   name varchar(20),                   sex char(2),                   ID char(11),                   class varchar(20)                 );

增:

1.使用insert將具體指直接插入表中:

         語法:insert [into]<表名> [列名] values <列值>

    例:insert into Students (name,ID,class) values ('陳雨豪','16408070619','軟工1603');

2.使用insert將select語句的查詢結果新增到已有的表中:

        語法:insert into <表名> <列名> select <列名> from <表名>

   例:insert into Score (姓名,學號,班級)

                    select name,ID,class         

                    from  Strdents;

      注意:查詢得到的資料個數、順序、資料型別等,必須與插入的項保持一致

刪:

1.使用delete刪除表中某些元組

    語法:delete from <表名> [where <刪除條件>]    

    例:delete from Students

           where name='陳雨豪'(刪除表Students中name列值為‘陳雨豪’的行) 

    注意:delete刪除的是元組,所以在delete後面不能出現欄位名

               刪除表的所有行,但表的結構、列、約束、索引等不會被刪除

改:

 使用update更新修改資料         

    語法:update <表名> set <列名=更新值> [where <更新條件>] 

    例:update Students set class='軟工1801' where name = '陳雨豪';

查:

單表查詢:

    語法:select <列名> from <表名> [where <查詢條件表達試>] [order by<排序的列名>[asc或desc]]

   1).查詢表中所有資料行和列

    例:select *

                      from Students

    說明:查詢a表中所有行和列

   2).條件查詢

    例:select name  

                      from  Students  

                      where class = '軟工1603';

    說明:查詢表Students中班級為‘軟工1603’的所有行,並顯示姓名

               注意:多個條件之間應該使用適當的謂詞進行連線

   3).在查詢中使用as更改列名

    例:select name as 姓名 

                      from Students

                       where  class='軟工1603';

    說明:查詢Students表中班級為‘軟工1603’的所有行,顯示name列,並將name列改名為姓名顯示

   4).查詢空行

    例:select name

                      from Students

                      where class is null;

    說明:查詢表Students 中class 為空的所有行,並顯示name列(SQL語句中用is null或者is not null來判斷是否為空行)

   5)查詢返回限制行數

    例:select top 6 name

                     from Students;

    說明:查詢表Students,顯示列name的前6行

   6).查詢排序

    例:select name

      from Score

      where grade>=60 

      order by desc;

    說明:查詢表中成績大於等於60的所有行,並按降序顯示name列(desc為降序,asc為升序)

   7).使用like進行字元匹配

    例:select *

                     from Students

                     where name like '陳%';

    說明:查詢顯示錶Students 中,name欄位第一個字為陳的記錄

               注意:萬用字元%代表任意長度,_代表單個字元

   8).使用between在某個範圍內進行查詢

    例:select *

                      from Students

                      where age between 18 and 20;

    說明:查詢顯示錶Students 中年齡在18到20之間的記錄

   9).使用group by進行分組查詢

    例:select name

      from Students

      group by class

               說明:查詢Students表中name欄位的所有記錄,並按照class欄位進行分組

           10).使用having子句進行分組篩選

    例:select name    

      from Students

      group by class

      having count(*)>30

    說明:查詢Students表中班級人數大於30的班級的學生的姓名