SQL學習 常用語法2

2021-08-22 07:08:51 字數 2815 閱讀 7356

1. drop 語句:撤銷索引、撤銷表以及撤銷資料庫

1)drop index 語句:刪除表中的索引

alter table table_name drop index index_name(mysql中)

2)drop table 語句用於刪除表

drop table table_name

3)drop database 語句用於刪除資料庫

drop database database_name

4)truncate table:僅僅刪除表內的資料,但並不刪除表本身

truncate table table_name

2. alter table 語句:在已有的表中新增、刪除或修改列。

alter table table_name add column_name datatype

alter table table_name drop column column_name

alter table table_name modify column column_name datatype // 改變資料型別

3. auto_increment欄位:auto-increment 會在新記錄插入表中時生成乙個唯一的數字。

下面的 sql 語句把 "persons" 表中的 "id" 列定義為 auto-increment 主鍵字段:(mysql)

create table persons

(id int not null auto_increment,

lastname varchar(255) not null,

firstname varchar(255),

address varchar(255),

city varchar(255),

primary key (id)

)預設地,auto_increment 的開始值是 1,每條新記錄遞增 1。

要讓 auto_increment 序列以其他的值起始,請使用下面的 sql 語法:

alter table persons auto_increment=100

在 "persons" 表中插入新記錄,我們不必為 "id" 列規定值(會自動新增乙個唯一的值):

insert into persons (firstname,lastname) values ('lars','monsen')

給已經存在的colume新增自增語法:

alter table table_name change column_name column_name data_type(size) constraint_name auto_increment;

alter table student change id id int( 11 ) not null auto_increment;

4. 檢視(views)

1) create view 語法

create view view_name as

select column_name(s)

from table_name

where condition

2)如果是想新增列等操作,必須重新更新檢視

create view [current product list] as

select productid,productname,category

from products

where discontinued=no

3)撤銷檢視

drop view view_name

5. date函式

1)內建日期函式:

now() 返回當前的日期和時間

curdate() 返回當前的日期

curtime() 返回當前的時間

date() 提取日期或日期/時間表示式的日期部分

extract() 返回日期/時間的單獨部分

date_add() 向日期新增指定的時間間隔

date_sub() 從日期減去指定的時間間隔

datediff() 返回兩個日期之間的天數

date_format() 用不同的格式顯示日期/時間

2)date資料型別

mysql 使用下列資料型別在資料庫中儲存日期或日期/時間值:

date - 格式:yyyy-mm-dd

datetime - 格式:yyyy-mm-dd hh:mm:ss

timestamp - 格式:yyyy-mm-dd hh:mm:ss

year - 格式:yyyy 或 yy

6. null值

預設地,表的列可以存放 null 值。null 用作未知的或不適用的值的佔位符。

select lastname,firstname,address from persons where address is null

select lastname,firstname,address from persons where address is not null

7. null函式

如果unitsonorder不是null,則返回unitsonorder,是null,則返回0

select productname,unitprice*(unitsinstock+ifnull(unitsonorder,0)) from products

select productname,unitprice*(unitsinstock+coalesce(unitsonorder,0)) from products // 返回第乙個非空值,支援在多個引數中找到非空值,isnull只支援乙個

mysql常用語法 MySQL常用語法

更新資料 update 表名 set 健名 更改的值 where 建 刪除資料 delete from 表名 where 索引 create index 索引名稱 on 表名 鍵名 建立試圖 create view 檢視名 鍵,鍵 as select matchno,abs won lost fro...

mysql基本常用語法 mysql 常用語法

1.1.開啟 service mysql start 1.2.關閉 service mysql stop 1.3.重啟 service mysql restart 2.1.密碼明文 語法 mysql u使用者名稱 p使用者密碼 舉例 mysql uroot p123456 2.2.密碼密文 語法 m...

c語言常用語法2

1 sprintf 很好用的乙個函式可以將整數轉換成字串,可以替代itoa linux下不存在 include int sprintf char str,const char format,2 fprintf int fprintf file stream,const char format,3 s...