1. 程式人生 > 其它 >sql基礎語法

sql基礎語法

1.註釋語句:

#單行註釋
/*多行註釋
註釋
*/
-- 單行註釋,注意有註釋符號和輸入中間有空格

2.表結構語句:

  新建表:

create table t3(
    id int not null primary key, # id為主鍵,且不能為空
    name char(20) not null
    ); 
語法:語法 create table 表名稱( 欄位名 欄位名型別 欄位描述符,欄位名 欄位型別 欄位描述符);

  刪除表:

drop table t3;
語法:drop table 表名稱;

  修改表:

alter table t2 add(score int
not null); #新增列(欄位,且不能為空)
語法:alter table 表明稱 add(欄位名 型別 描述符);
alter table t2 drop column score; #刪除列
語法:alter table 表名 drop colunm 欄位名,drop colunm 欄位名;
alter table t2 change name score int(22) not null; #修改列
語法:alter table 表名 change 舊欄位名 新欄位名 新欄位描述符

3.資料型語句:

  新增資料:

insert into t2 values(007,22),(008
,33); #全欄位插入
語法:insert into 表名 values(欄位1值,欄位2值,……),(欄位1值,欄位2值,……);
insert into t2(id,name) values(10,82); # #個別欄位插入
語法:insert inton 表名(欄位名) values(值一),(值二);
   insert inton 表名(欄位名,欄位名) values(值一),(值二);

  刪除資料:

delete from t2 where id=4;
語法:delete from 表名 where 條件;(不加條件時:刪除整張表資料)

  修改資料:

update t2 set
score=69 where id=2;
語法:update 表名 set 更改的欄位名=值 where 條件;

  查詢資料:

單表查詢:
select
* from t2; #單表查詢
語法:select * from 表名;
select id from t1; #個別欄位查詢
語法:select 欄位一,欄位二 from 表名;
多表查詢
select
name from t3 where id=(select id from t2 where score=55); #巢狀查詢 語法:select 欄位一,欄位二…… from 表名 where 條件(查詢); (select id from t3 )union(select id from t2); #並查詢:union前後查詢語句返回的資料數量必須一致 select id from t3 where id in (select id from t2); # 交查詢

  常用函式:

select sum(score) from t2;        #求和
select avg(score) from t2;         #求平均值
select count(*) from t2;            #計數(不包含null)
select max(score) from t2;        #最大值
select min(score) from t2;        #最小值

  常用修飾符:

select distinct score from t2;        #distinct 欄位中值唯一
select * from t2 limit 2;                    #結果數限制
select * from t2 order by score;    #排序(預設升序)
select * from t2 order by score desc;        #降序排序
select * from t2 order by score asc;        #升序排序
select score from t2 group by score;    #分組