sql學習網址:http://www.w3school.com.cn/sql/index.aspmysql
1>建立數據庫sql
Create Database if not exists 【myDatabase】;數據庫
2>刪除數據庫學習
Drop Database if exists 【myDatabase】;spa
3>建立表 刪除表blog
create table student (id int(5) primary key,name varchar(10) not null,classid int(4));索引
drop table if exists studentrem
4>給已經存在的表加主鍵、外鍵、索引it
alter table student add primary key(id); //加主鍵索引io
alter table student add constraint f_class foreign key(classid) references class(id); //加外鍵
alter table student add index(id); //加通常索引
alter table student add unique(id); //加惟一索引
5>給字段設置自增加(只有int類型的才能設置自增加)
alter table student change id id int auto_increment;
6>追加一個新的字段
alter table class add (sumstu int(2));
7>查看數據庫,表結構
show databases; //查看數據有哪些
show tables; //查看有哪些表
show columns from student; //查看改表的列
8>插入數據(insert)
insert into student (name,sex,classid) values("小明","男",1); //classid是外鍵關聯(此種狀況正常插入便可,系統會自動到關聯表的主鍵中查找,若是沒有插入失敗)
9>更新數據(update)
uodate student set name="小明" where id=1;
10>刪除數據(delete)
delete from student where id=1;
11>查詢數據(select)
select * from student;
12>查詢過濾重複數據(distinct)
select distinct name from student;
13>limit offset的用法(limit 2 offset 3 從第三條開始查兩條 <=> 等價於 limit 3,2)
select * from class limit 3,2; <=等價=> select * from class limit 2 offset 3;
14>查詢時where條件like、not like(% 表明任意字符,_表明一個字符)
select * from student where englishname like "_";
select * from student where englishname like "xiao%";
15>查詢時where條件IN、not In (in的後面是一個集合)
select * from student where
16>查詢時where條件between A and B(mysql中返回的結果包括兩個邊界A和B)
select * from student where id between 1 and 5;
關聯查詢:表結構
1> 內鏈接(inner join <=等價=> join) 後面的條件關鍵字能夠是on 或 where
select c.grade,c.name,s.name,s.sex from class as c inner join student as s where(on) c.id=s.classid;
select c.grade,c.name,s.name,s.sex from class as c join student as s where(on) c.id=s.classid;
2>笛卡兒積 (cross join) 後邊不加條件,若是加條件和以上內鏈接同樣的效果
select c.grade,c.name,s.name,s.sex from class as c cross join student as s;
3>外鏈接的一種-----左鏈接(left join on) 這裏的條件關鍵字只能用on(親測):左鏈接是以左邊的表爲基準
select c.grade,c.name,s.name,s.sex from class as c left join student as s on c.id=s.classid;
4>外鏈接的一種-----右鏈接(right join on) 這裏的條件關鍵字只能用on(親測): 右鏈接是以右邊的表爲基準
select c.grade,c.name,s.name,s.sex from class as c right join student as s on c.id=s.classid;
5>union <=幾乎等價=> union all (將兩個表的數據結合起來,要求:兩個表所查的列數必定要相等)
select name,grade from class union(union all) select name,sex from student;