常用關系數據庫
SQLiteMySQLOracle數據庫是如何存儲數據的:數據庫的存儲結構和Excel很像,以表(table)為單位
數據庫儲存數據的步驟 新建一張表(table)添加多個字段(column、列、屬性)添加多個記錄(row、每行存放多個字段對應的值)創建表
格式(一般表名以t_作為前綴) create table表名(字段名1 字段類型1,字段名2 字段類型2,…);create table if not exists 表名(字段名1 字段類型1,字段名2 字段類型2,…);字段類型
integer:整形值real:浮點值text:文本字符串blob:二進制數據(比如文件)例子create table t_student (id integer, name text, age integer, score real);刪除表
格式
drop table 表名drop table if exists 表名例子:drop table t_student;插入數據(insert)
格式:
insert into 表名(字段1,字段2,…)values(字段1的值,字段2的值,…);注意:數據庫中的字符串應該使用單引號‘括住
例子
insert into t_student (name,age) values ('hyq', 22);更新數據(update)
格式 update 表名 set 字段1 = 字段1的值,字段2 = 字段2的值,…;例子
update t_student set name = 'xiaoqiu',age = 99;結果 將t_student表中所有記錄的name改為xiaoqiu,age改為99刪除數據(delete)
格式 delete from 表名;例子
delete from t_student;結果 將t_student表中的所有字段的所有記錄都刪除 select name,age from t_student; select * from t_student;            重命名字段名
格式 select 字段1 別名,字段2 別名,… from 表名 別名;select 字段1 別名,字段2 as 別名,… from 表名 as 別名;例子
給name起個叫做myname的別名,給age起個叫做myage的別名selete name myname, age myage from t_student;給t_student表起個別名叫做s,利用s來引用表中的字段select s.name, s.age from t_student s;統計 格式 select count [字段] from 表名select count [*] from 表名示例 select count(age)from t_student;&&where 字段1 = 某個值 or 字段2 = 某個值;//or等同于C語言中的||  例子
將t_student表中大于10并且名字不等于hyq的記錄,年齡都改為18update t_student set age = 18 where age > 10 and name != 'hyq';查詢出來的結果可以用order by進行排序
select * from t_student order by age;默認是按照升序排序(由小到大),也可以變為降序
select * from t_student order by age asc; //升序select * from t_student order by age desc; //降序可以按照多個字段進行排序
select * from t_student order by age asc ,height desc; //年齡升序,身高降序建表時可以給特定的字段設置一些約束條件,常見的約束有
not null:規定字段的值不能為nullunique:規定字段的值必須唯一default:指定字段的默認值create table t_student (id integer,name text not null unique,age integer not null default 1);主鍵 PRimary Key,用來唯一地標識某一條記錄t_student表中,若沒有設置一個字段為主鍵,則難免會出現幾個記錄中name和age完全相等的情況,因此需要一個標識來區分,比如人的省份證id,來區分同名同齡的人主鍵可以是一個或者多個字段主鍵應當不影響用戶記錄的數據,最好是由電腦自動生成主鍵主鍵聲明
在創建的時候用primary key聲明一個主鍵,eg:用一個integer類型的id字段作為t_student表的主鍵create table t_student(id integer primary key, name text, age integer);主鍵字段默認就包含了not null和unique兩個約束讓integer類型的主鍵自動增長,需要添加autoincrement,一般情況下主鍵自動增加便于管理 create table t_student (id integer primary key autoincrement, name text, age integer) ;外鍵約束
利用外鍵約束可以用來建立表與表之間的聯系;一個表中的一個字段來自另一個表里的一個字段eg:學生表的班級字段,來自班級表中的id字段 create table t_student (id integer primary key autoincrement, name text, age integer, class_id integer, constraint fk_t_student_class_id_t_class_id foreign key (class_id) (id)) ; references t_class連接表查詢
如果需要聯合多張表才能查詢到想要的數據,一般需要使用表連接表連接的基礎 內連接:inner join 或者join(顯示的是左右表都有完整字段值得記錄)左外連接:left outer join (保證左表數據的完整性)eg:查詢計算機1班的所有學生 select s.name,s.age from t_student s, t_class c where s.class_id = c.id and c.name = '計算機1班';from語句組裝來自不同數據源的數據where語句基于指定的條件對記錄進行篩選 where語句中是不能用狙擊函數作為條件表達式的where語句用于基本表或視圖,從中選擇滿足條件的元組 group by語句將數據劃分為多個分組使用聚合函數進行計算(常用聚合函數:count、sum、avg、max、min) max函數返回一列中的最大值,NULL值不包括在計算中使用having語句篩選分組計算所有表達式使用order by對結果進行排序   | 
 
 | 
新聞熱點
疑難解答