DDL:
create table if not exists t_class (id integer primary key autoincrement,name text);
drop table t_class;
DML:
insert into t_student (name,age) values ('chenrong',18);
delete from t_class where id=1;
update t_class set name = 'rachel' where id=2;
update t_class set name = 'rachel' , age = '18' where id=2;
SQL:
select * FROM t_student;
select * from t_student order by age desc ; //降序
select * from t_student order by age asc ; // 升序(默認(rèn))
imit常用來做分頁查詢,比如每頁固定顯示5條數(shù)據(jù),那么應(yīng)該這樣取數(shù)據(jù)
第1頁:limit 0, 5
第2頁:limit 5, 5
第3頁:limit 10, 5
…
第n頁:limit 5*(n-1), 5
猜猜下面語句的作用
select * from t_student limit 7 ;
相當(dāng)于select * from t_student limit 0, 7 ;
表示取最前面的7條記錄
普通約束 , 主鍵約束:
create table if not exists t_student (id integer primary key autoincrement,name text not null unique,age integer not null default 1);
外鍵約束:
利用外鍵約束可以用來建立表與表之間的聯(lián)系
外鍵的一般情況是:一張表的某個(gè)字段,引用著另一張表的主鍵字段
班級(jí)表 :
create table if not exists t_class (id integer primary key autoincrement,name text);
學(xué)生表:
create table if not exists t_student (id integer primary key autoincrement,name text,age integer,class_id integer,constraint fk_student_class foreign key (class_id) references t_class(id));
t_student表中有一個(gè)叫做fk_student_class的外鍵
這個(gè)外鍵的作用是用t_student表中的class_id字段引用t_class表的id字段
表連接查詢:
什么是表連接查詢
需要聯(lián)合多張表才能查到想要的數(shù)據(jù)
1:
select s.name sName,c.name cName from t_student s,t_class c;
會(huì)把所有結(jié)果查出來
2正確的察法:
select s.name sName,c.name cName from t_student s,t_class c where s.class_id = c.id;
多表查詢
***連接不需要外鍵約束,這不是必要條件 ***
****left join(表名) on 條件等式
select * from t_person p left join t_book b on p.book_id= b.id
****代碼意義
左連接,把t_person表跟t_book表聯(lián)系起來,而查詢的結(jié)果的條件是t_person.book_id= t_book.id
****關(guān)于Left Join跟Join的選擇:
left join
如果要查詢左邊表中的所有符合條件的數(shù)據(jù),使用left jion
通常查詢出來的結(jié)果會(huì)多,因?yàn)橛疫叡聿淮嬖诘挠涗洠瑯涌赡軙?huì)被查詢出來,查詢出來之后,右邊表不存在的記錄,全部為NULL
<br />join
如果要兩個(gè)表中同時(shí)存在的符合條件的數(shù)據(jù),使用jion
通常查詢出來的結(jié)果會(huì)比左連接少,因?yàn)橛疫叡聿淮嬖诘挠涗洠粫?huì)顯示出來