域完整性:主鍵primary key;外鍵foreign key;
建立一個資料庫:create database 庫名;
創建表及列名:create table表名(
列名1 數據類型 約束,
列名2 數據類型 約束,
列名3 數據類型 約束);
例:
->id int(10) not null primary key,
->name varchar(20) not null);
在已創建的表中添加列:alter table表名 add列名屬性;
在已創建的表中修改列的屬性:alter table表名 change (原)列名
(改後)列名 (改後)屬性;
主鍵及自增:id int(10) not null primary keyauto_increment
刪除表:drop table表名;
刪除資料庫:drop database庫名;
向表中添加一條記錄:insert into表名(列名1,列名2)values(**,**);
向表中添加多條記錄:insert into表名(列名1,列名2)
values(**,**),
(**,**),
(**,**),
(**,**);
更改記錄操作:update表名 set列名=更新值 where更新條件;
例如:update student set sname="Tom" where sname="Alex";
刪除記錄操作:delete from表名 where刪除條件
例如:delete from student where sage<18;
查詢記錄操作:select列名 from表名 where查詢條件 order by列名 asc/desc;
例如:select * from student;
使用集函數:count(列名)計算元素的個數
sun(列名)對某一列值求和,但必須是整數
avg(列名)對某一列的值計算平均值
max(列名)找出某一列的最大值
min(列名)找出某一列的最小值
例如:1.查詢學生總數
select count(*) from student;
2.查詢選修課程的學生人數
select count(distinct studentid) from sc;
3.查詢1號課程的學生平均成績
select avg(grade) from sc where courseid=1;
4.查詢1號課程的學生最高分和最低分
select max(grade) as '最高分',min(grade) as '最低分
from sc where courseid=1;
5.查詢每個學生的平均成績
select studentid,avg(grade) as '平均成績' from sc
group by studentid ;
6.查詢學生的平均成績在70分以上的
select studentid,avg(grade) as '平均成績' from sc
group by studentid having avg(grade)>70;
把重復的數據查出來:
語法:Select * From 表 Where 重復字段 In (Select 重復字段 From 表 Group By 重復字段 Having Count(*)>1)
例如:select * From A where name in (select name from A group by id having count(1) >= 2)