數(shù)據(jù)庫
創(chuàng)建
create database database_name
創(chuàng)建testdb數(shù)據(jù)庫并支持中文
create database testdb charset "utf8";
刪除
drop database database_name
顯示數(shù)據(jù)庫
show databases
使用數(shù)據(jù)庫
use database_name
數(shù)據(jù)表
顯示數(shù)據(jù)表
show tables
查看創(chuàng)建表結構的信息
show create table table_name
刪除指定數(shù)據(jù)表
drop table table_name
創(chuàng)建數(shù)據(jù)表
create table table_name(column_name, column_type)
創(chuàng)建一個student表
create table student(
stu_id INT NOT NULL AUTO_INCREMENT,
name CHAR(32) NOT NULL,
age INT NOT NULL,
register_date DATE,
PRIMARY KEY ( stu_id )
);
設置為NULL數(shù)據(jù)類型,這字段必須填入數(shù)據(jù)
AUTO_INCREMENT定義列為自增的屬性,一般用于主鍵,數(shù)值會自動加1。
PRIMARY KEY關鍵字用于定義列為主鍵。 您可以使用多列來定義主鍵,列間以逗號分隔。
修改數(shù)據(jù)表名稱
alter table table_name rename new_table_name
查看數(shù)據(jù)表的數(shù)據(jù)結構
desc table_name
插入數(shù)據(jù)
INSERT INTO table_name ( field1, field2,...fieldN )
VALUES (value1,value2,...valueN )
向student數(shù)據(jù)表中插入一條數(shù)據(jù)
insert into student (name,age,register_date) values ("alex li",22,"2016-03-4");
查詢數(shù)據(jù)
SELECT column_name,column_name
FROM table_name
[WHERE Clause]
[OFFSET M ][LIMIT N]
select * from student limit 3 offset 2;
select * from student limit 3 ,1;
使用 LIMIT 屬性來設定返回的記錄數(shù)。
通過OFFSET指定SELECT語句開始查詢的數(shù)據(jù)偏移量。默認情況下偏移量為0。
更新數(shù)據(jù)庫字段內(nèi)容
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
update student set age=22 ,name="Alex Li" where stu_id>3;
刪除數(shù)據(jù)庫字段內(nèi)容
DELETE FROM table_name [WHERE Clause]
delete from student where stu_id=5;
刪除,添加或修改表字段
刪除
alter table table_name drop column_name
從student表刪除register_date 字段
alter table student drop register_date;
添加
alter table table_name add column_name column_type
添加phone字段
alter table student add phone int(11) not null;
修改字段類型
alter table table_name modify column_name new_column_type
修改phone字段類型
ALTER TABLE testalter_tbl MODIFY phone CHAR(10);
修改字段類型及名稱
alter table table_name change column_name new_column_name new_column_type
修改phone字段類型及名稱
ALTER TABLE student change phone email text;
更改字段類型時,not null用default設置默認值
ALTER TABLE student add phone int not null default 1783567321;
SQL FOREIGN KEY 約束
FOREIGN KEY 約束用于預防破壞表之間連接的動作。
FOREIGN KEY 約束也能防止非法數(shù)據(jù)插入外鍵列,因為它必須是它指向的那個表中的值之一。
CREATE TABLE class
(
id int NOT NULL auto_increment,
grade char(10) NOT NULL,
id_s int,
PRIMARY KEY (id),
FOREIGN KEY (id_s) REFERENCES student(id)
)