簡明SQL初級教程

簡明MySQL教程

創建新user並添加password及權限

■創建用戶scott,密碼爲tiger

create user 'scott'@'localhost' identified by 'tiger'

■添加用戶權限:

grant select, insert, update, delete, create, create view, drop,
    execute, references on *.* to 'scott'@'localhost';

■ 若要啓用遠程數據庫連接,並賦予所有操作權限則:

    grant all privileges on *.* to 'scott'@'%' identified by 'tiger';

■ 若僅僅開放某個IP地址的數據庫操作權限,則:

    grant all privileges on *.* to 'scott'@'ipAddress'identified by 'tiger';

create 和 drop

■創建table:

create table Course (
    courseID char(5),
    subjectID char(4) not null,
    courseNumber integer,
    title varchar(50) not null,
    numOfCredits integer,
    primary key(courseID)
);

create table Student (
    ssn char(9),
    firstName varchar(25),
    mi char(1),
    lastName varchar(25),
    birthDate date,
    street varchar(25),
    phone char(11),
    zipCode char(5),
    deptId char(4),
    primary key(ssn)
);

create table Errollment (
    ssn char(9),
    courseID char(5),
    dateREgistered date,
    grade char(1),
    primary key (ssn, courseID),
    foreign key (ssn) references 
        Student(ssn),
    foreign key (courseID) references
        Course(courseID)
);

■刪除table

drop table Course;

insert, update, delete

■插入數據項

insert into Course (courseId, subjectId, courseNumber, title, numOfCredits)
values ('11113', 'CSCI', '3720', 'Database Systems', 3);

■更新數據項信息

update Course
set numOfCredits = 4
where title = 'Database Systems';

■刪除table

delete from Course
where title = 'Database Systems';

like, between-and, is null關鍵字

■like:

lastName like '_mi%'表示第2字母爲m,第3個字字母爲i的字符串lastName,其中_表示單個字符,%表示多個字符

■between, and:

v between v1 and v2 等價於 v >= v1 and v <= v2
v not between v1 and v2 等價於 v < v1 or v > v2.

■null

v is null 
v is not null

■應用:

select ssn
from Enrollment
where grade between 'C' and 'A';

列的別號

由於create一個新的table的時候,colome中不能含有空格,因此,顯示錶格的時候可讀性會降低,因此,使用別號顯示可以增強描述性,如下應用:

select lastName as "Last Name", zipCode as "Zip Code"
from Student
where deptId = 'CS';

使用算術運算符

+, -, *, /都可以在sql中使用
假設每節課有50min,則打印總課時的命令如下:

select title, 50 * numOfCredits as "Lecture Minutes Per Week"
from Course
where subjectId = 'CSCI';

distinct消除重複元素

當有重複元素時,採用distinct關鍵字:

select distinct subjectId as "Subject ID"
from Course;

當選擇多個列的時候,當且僅當兩個列的元素完全相同才消除:

select distinct subjectId, title
from Course;

order有序顯示數據

desc爲降序,asc爲升序:

select lastName, firstName, deptId
from Student
where deptId = 'CS'
order by lastName desc, firstName asc;

聯繫多個數據表格

select distinct lastName, firstName, courseId
from Student, Enrollment
where Student.ssn = Enrollment.ssn and
lastName = 'Smith' and firstName = 'Jacob'
發佈了27 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章