> create database school; 建立數據庫school > use school; 進入數據庫 > create table class (id int,name char(10),score decimal(5,2)); 建立一個表class(id整數 name字符串10個 成績 數據長度5 小數點後面保留2位) > insert into class (id,name,score) values (1,'zhangsan',70.5); > insert into class (id,name,score) values (2,'lisi',80.5); 寫入數據 > alter table class add address varchar(50) default'地址不詳' 增長一個列
> update class set name='wangwu' where id=1; zhangsan改爲wangwu 修改位置是id=1的列
> show databases; 查看數據庫 > use school; 進入數據庫 > show tables; 查看全部表(須要進入數據庫查看) > desc class; 查看class表的結構 > select * from class; 查看class表的全部數據 > select name from class; 查看class表的指定列 > select distinct * from class; 查看全部數據 (且不重複) > select * from class where score>85; 條件查看(查看score>85的) > select * from class where score>85 and score<90; (查看大於85 小於90的數據) > select * from class where exists (select * from class where score<90) and score<80; 使用exists查詢 先查詢小於90的人 再在小於的90的數據中 查詢 小於80的數據 最終顯示
delete from class where id=2; 刪除id爲2的行
alter table class drop column address ; 刪除address列
drop table class; 刪除整個表
drop database school; 刪除數據庫面試
建立一個數據庫和表 來演示下索引操做sql
> create database school; > use school; > create table class (id int(4) not null primary key auto_increment,name char(10) not null,score decimal(5,2),address varchar(50) default'地址不詳',hobby int(4))charset=utf8; > insert into class (name,score,address,hobby) values ('zhangsan',70.5,'金川校區',2); > insert into class (name,score,address,hobby) values ('lisi',80.5,default,2);
普通索引數據庫
create index name_index on class(name); 建立索引
show index from class; 查看索引
drop index name_index on class; 刪除索引ide
惟一索引3d
create unique index name_index on class(name); 建立索引
drop index name_index on class; 刪除索引code
> create table hob (hid int,hobname char(10) not null); 建立表用來關聯 > select c.id,c.name,c.score,c.address,h.hobname from class c inner join hob h on c.hobby=h.hid; 查看(class別名c,hob別名h)class表id,name,score,address.。 hob表的hobname 將class表的hobby 關聯hob的hid。 (注意:這只是查看) > create temporary table tempclass (select c.id,c.name,c.score,c.address,h.hobname from class c inner join hob h on c.hobby=h.hid); (生成臨時表class 注意:臨時表show tables; 查詢不到 去掉參數temporary則會生成永久的表) > select * from class_hob; 查看class_hob臨時表。