標籤:style 分組 arc reference int group one sql 修改
SQL語句
建立表:
1 create table 表名(2 列名 類型 是否可以為空白,3 列名 類型 是否可以為空白4 )ENGINE=InnoDB DEFAULT CHARSET=utf8;
1 create table school( 2 nid int not null primary key, 3 name varchar(20) 4 )engine=innodb default charset=utf8; 5 6 create table student( 7 nid int not null primary key, 8 name varchar(20), 9 age int,10 school_id int not null,11 constraint fk foreign key (school_id) references school(nid)12 )engine=innodb default charset=utf8;
外鍵
修改表結構:
1 添加列:alter table 表名 add 列名 類型; 2 刪除列:alter table 表名 drop column 列名; 3 4 修改列: 5 alter table 表名 modify column 列名 類型; 6 alter table 表名 change 原列名 新列名 類型; 7 8 添加主鍵:alter table 表名 add primary key(列名); 9 10 刪除主鍵:alter table 表名 drop primary key;11 12 添加外鍵:alter table 從表 add constraint 外鍵名稱 foreign key 從表(外鍵欄位) references 主表(主鍵欄位);13 刪除外鍵:alter table 表名 drop foreign key 外鍵名稱;
1 1.增: 2 insert into 表 (列名1,列名2...) values (值1,值2...),(值1,值2...); 3 insert into 表1 (列名1,列名2...) select 列名1,列名2,... from 表2; 4 5 2.刪: 6 delete from 表 where id=1 and name=‘yan‘; 7 8 3.改: 9 update 表 set name = ‘yan‘ where id>1;10 11 4.查:12 select nid,name,age as 別名 from 表 where id>1;
3.條件查詢:
1 select * from 表 where id>1 and name!=‘yan‘ and age=21;2 select * from 表 where id between 1 and 9;3 select * from 表 where id in (1,2,3);4 select * from 表 where id not in (1,2,3)5 select * from 表 where id in (select nid from 表);
萬用字元查詢:
1 select * from 表 where name like ‘yan%‘ ;2 select * from 表 where name like ‘yan_‘ ;
限制查詢:
1 select * from 表 limit 5; - 前5行2 select * from 表 limit 4,5; - 從第4行開始的5行3 select * from 表 limit 5 offset 4 - 從第4行開始的5行
排序查詢:
1 select * from 表 order by 列 asc; - 根據 “列” 從小到大排列2 select * from 表 order by 列 desc; - 根據 “列” 從大到小排列3 select * from 表 order by 列1 desc,列2 asc; - 根據 “列1” 從大到小排列,如果相同則按列2從小到大排序
分組查詢:
1 select num from 表 group by num;2 select num from 表 group by num having max(id)>10;
連表查詢:
1 select A.num, A.name, B.name2 from A 3 left join B4 on A.nid = B.nid
MySQL常用語句: