XAMPP
来用 PhpMyAdmin
创建数据库
CREATE SCHEMA name;
CREATE DATABASE name;
Use name;
CREATE TABLE [IF NOT EXISTS] name (
col-name datatype [col-options],
:
col-name datatype [col-options],
[constraint-1],
:
[constraint-n]
);
-- Contents between [] are optional
###1.3 Data Types
Data Type | 属性 |
---|---|
SMALLINT[(M)] [UNSIGNED] [ZEROFILL] | 2 Bytes, signed range: -32768 to 32767 |
MEDIUMINT[(M)] [UNSIGNED] [ZEROFILL] | 3 Bytes |
INT[(M)] [UNSIGNED] [ZEROFILL] | 4 Bytes |
BIGINT[(M)] [UNSIGNED] [ZEROFILL] | 8 Bytes |
DECIMAL / DEC / NUMERIC / FIXED[(M[,D])] [UNSIGNED] [ZEROFILL] | M大小 1~65 |
FLOAT§ [UNSIGNED] [ZEROFILL] | automatically choose single precision or double precision based on the value of p |
CHAR[(M)] | 1 Byte, M is the length, 0 ~ 255 |
VARCHAR(M) | A variable-length string, M is 0 to 65,535 |
数据类型 | 描述 |
---|---|
DATE | YYYY-MM-DD |
DATETIME[(fsp)] | ‘YYYY-MM-DD hh:mm:ss[.fraction]’ |
TIMESTAMP | UTC time |
###1.4 Column Options
col-name datatype [col-options]
NOT NULL
UNIQUE
DEFAULT value
AUTO_INCREMENT = baseValue
ALTER TABLE Persons AUTO_INCREMENT = 100;
INSERT INTO tablename (col1, col2, …)
VALUES (val1, val2, …),
:
(val1,val2,val3);
INSERT INTO tablename VALUES (val1, val2, …);
UPDATE table-name
SET col1 = val1 [,col2 = val2…]
[WHERE condition]
DELETE FROM
table-name
[WHERE condition]
CREATE TABLE name (
col-name datatype [col-options],
:
col-name datatype [col-options],
[constraint-1],
:
[constraint-n]
);
CONSTRAINT name TYPE details;
PRIMARY KEY
UNIQUE
FOREIGN KEY
INDEX
CREATE TABLE People (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
sex CHAR NOT NULL CHECK (sex IN ('M','F')),
CONSTRAINT id_positive CHECK (id > 0)
);
CONSTRAINT name UNIQUE (col1, col2, …)
CONSTRAINT name PRIMARY KEY (col1, col2 …)
CONSTRAINT name
FOREIGN KEY
(col1, col2, ...)
REFERENCES
table-name
(col1, col2, ...)
[ON UPDATE ref_opt
ON DELETE ref_opt]
-- ref_opt: RESTRICT | CASCADE | SET NULL | SET DEFAULT
CREATE TABLE `branch` (
`branchNo` char(4) BINARY NOT NULL,
PRIMARY KEY (`branchNo`),
...);
RESTRICT
– stop the user from doing it
CASCADE
– let the changes flow on
SET NULL
– make referencing values null
SET DEFAULT
– make referencing values the default for their column
These options can be applied to one or both kinds of the table updates:
CONSTRAINT `FK_staff_branchNo`
FOREIGN KEY (`branchNo`)
REFERENCES `branch` (`branchNo`)
ON DELETE SET NULL
ON UPDATE CASCADE
ALTER TABLE table_name
ADD column_name datatype [options like UNIQUE …];
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE table_name
CHANGE COLUMN
col_name new_col_name datatype [col_options];
ALTER TABLE table_name
MODIFY COLUMN
column_name datatype [col_options];
###3.5 Adding Constraints
ALTER TABLE table-name
ADD CONSTRAINT name definition;
ALTER TABLE table-name
DROP INDEX name | DROP FOREIGN KEY name | DROP PRIMARY KEY
-- INDEX - Can be used to drop unique keys
DROP TABLE [IF EXISTS] table-name1, table-name2…;
SELECT [DISTINCT | ALL]
column-list FROM table-names
[WHERE condition]
[ORDER BY column-list]
[GROUP BY column-list]
[HAVING condition]
SELECT col1[,col2…] FROM table-name;
select a, b, a+b as sum
from dup_test;
SELECT * FROM table-name
WHERE predicate;
LIKE
keyword to perform string comparisons in queriesSELECT * FROM books
WHERE bookName LIKE '%crypt%'
;
Like is not the same as ‘=’ because it allows wildcard characters
It is NOT normally case sensitive
The %
character can represent any number of characters, including none
The _
character represents exactly one character
SELECT * FROM table-name
WHERE date-of-event < '2012-01-01';
SELECT * FROM table-name
WHERE date-of-event LIKE '2014-11-%';
SELECT * FROM Table1, Table2;
TableName.ColumnName
SELECT column [AS] new-col-name
SELECT * FROM table [AS] new-table-name
Note: You cannot use a column alias in a WHERE clause
SELECT A.Name FROM
Employee A,
Employee B
WHERE
A.Dept = B.Dept
AND
B.Name = 'Andy';
SELECT col1 FROM tablename
WHERE col2 = (
SELECT col FROM tablename
WHERE condition)
SELECT columns FROM tables
WHERE col IN set;
SELECT columns FROM tables
WHERE col NOT IN set;
SELECT columns
FROM tables
WHERE EXISTS set;
SELECT columns
FROM tables
WHERE NOT EXISTS set;
val = ANY (set)
val = ALL (set)
SELECT * FROM A CROSSJOINB;
-- same as
SELECT * FROM A,B;
SELECT * FROM A INNERJOINBON condition
SELECT * FROM A INNERJOINBUSING (col1, col2)
SELECT * FROM A NATURALJOINB;
SELECT cols FROM
table1 type OUTER JOINtable2ON condition;
Full Outer Join in MySQL
(SELECT * FROM Student LEFT OUTER JOINEnrolment ON Student.ID = Enrolment.ID)
UNION
(SELECT * FROM Student RIGHT OUTER JOINEnrolment ON Student.ID = Enrolment.ID);
SELECT columns FROM tables
WHERE condition
ORDER BY cols [ASC|DESC]
SELECT COUNT | SUM | AVG | MIN | MAX (*) AS C FROM tablename;
The use of aggregate functions leads to all rows afterthefirst row being truncated.
SELECT column_set1 FROM tablesWHERE predicate
GROUP BY column_set2;
SELECT Name,
AVG(Mark) AS Average
FROM Grades
GROUP BY Name
HAVING
AVG(Mark) >= 40;
drop table if exists `activity`, `module_enrollment`, `student`, `modules`, `teachers`;
create table `teachers`
(
`id` int, -- we will add primary key later. NOT NULL and UNIQUE is not needed.
`name` varchar(200) not null,
`tel_no` varchar(40), -- not using INT here as we have numbers like +44
`office` varchar(15) not null
);
create table `modules`
(
`code` varchar(10), -- we will add primary key later. NOT NULL and UNIQUE is not needed.
`title` varchar(100) not null,
`teacher_id` int
);
create table `student`
(
`id` int(6), -- we will add primary key later. NOT NULL and UNIQUE is not needed.
`name` varchar(200) not null ,
`email` varchar(100) not null,
`enrolled_modules` varchar(255)
);
alter table `teachers` add primary key (`id`);
alter table `modules` add primary key (`code`);
alter table `student` add primary key (`id`);
-- The one below is a super key. Not a good choice:
-- alter table `student` add primary key (`student_id`, `student_name`);
alter table `modules` add
constraint fk_module_teacher foreign key (`teacher_id`)
references `teachers` (`id`)
insert into `teachers` values (6503399, 'John Drake', '12022017202020', 'SD-766');
insert into `modules` values ('HCI-101', 'Human Computer Interaction', 6503399);
insert into `teachers` values (7614411, 'Felicia Gomez', '1024', 'BES-207');
insert into `modules` values ('HSB', 'Haskell for Beginners', 7614411);
insert into `teachers` values (5899114, 'John Cartwright', '12345 ext 1212', 'BES-201');
insert into `modules` values ('MC1', 'Mathematics', 5899114);
-- Another way to insert data, if the module is not assigned with any teacher yet,
-- you can set it to be null and update it later
insert into `modules` values ('MC2', 'Advanced Mathematics', null); -- module is not assigned with teacher yet
insert into `teachers` values (7099543, 'Dave Moe', 'BES-205', '65432 ext 2121');
update `modules` set `teacher_id` = 7099543 where `code` = 'MC2'; -- update the teacher reference
alter table `student` add constraint fk_student_module
foreign key (`enrolled_modules`) references `modules` (`code`);
insert into `student` values (764411, 'Daryl', '[email protected]', 'MC1'); -- first module for daryl
-- insert into `student` values (764411, 'Daryl', '[email protected]', 'MC2');
-- You will get error: [23000][1062] (conn=40) Duplicate entry '764411' for key 'PRIMARY'
create table activity
(
`name` varchar(100) primary key,
`student_id` int(6),
`description` varchar(255),
constraint fk_activity_student foreign key (`student_id`) references `student` (`id`)
);
-- remove the primary key for student
-- alter table `student` drop primary key;
-- now try to add foreign key to `activity`.`student_id`
-- alter table `activity` add constraint fk_activity_student
-- foreign key (`student_id`) references `student` (`id`);
--
-- Does not work: Can't create table `jianjun`.`activity` (errno: 150 "Foreign key constraint is incorrectly formed")
-- Reason explained in the lab sheet
drop table if exists module_enrollment, activity, student, modules;
create table `modules`
(
`code` varchar(10) primary key,
`title` varchar(100) not null,
`teacher_id` int,
constraint fk_module_teacher foreign key (`teacher_id`) references `teachers` (`id`)
);
create table `student`
(
`id` int(6) primary key,
`name` varchar(200) not null,
`email` varchar(100) not null
);
create table module_enrollment
(
`enrollment_id` int primary key, -- this column is optional.
`module_code` varchar(10),
`student_id` int(6),
constraint fk_enrollment_module foreign key (`module_code`) references `modules` (`code`),
constraint fk_enrollment_student foreign key (`student_id`) references `student` (`id`)
);
###Data
drop table if exists `activity`, `module_enrollment`, `student`, `modules`, `teachers`;
create table `teachers`
(
`id` int primary key, -- we will add primary key later. NOT NULL and UNIQUE is not needed.
`name` varchar(200) not null,
`tel_no` varchar(40), -- not using INT here as we have numbers like +44
`office` varchar(15) not null
);
create table `modules`
(
`code` varchar(10) primary key,
`title` varchar(100) not null,
`teacher_id` int,
constraint fk_module_teacher foreign key (`teacher_id`) references `teachers` (`id`)
);
create table `student`
(
`id` int(6) primary key,
`name` varchar(200) not null,
`email` varchar(100) not null
);
create table module_enrollment
(
`enrollment_id` int primary key, -- this column is optional.
`module_code` varchar(10),
`student_id` int(6),
constraint fk_enrollment_module foreign key (`module_code`) references `modules` (`code`),
constraint fk_enrollment_student foreign key (`student_id`) references `student` (`id`)
);
create table activity
(
`name` varchar(100) primary key,
`student_id` int(6),
`description` varchar(255),
constraint fk_activity_student foreign key (`student_id`) references `student` (`id`)
);
insert into `teachers` values (6503399, 'John Drake', '12022017202020', 'SD-766');
insert into `modules` values ('HCI-101', 'Human Computer Interaction', 6503399);
insert into `teachers` values (7614411, 'Felicia Gomez', '1024', 'BES-207');
insert into `modules` values ('HSB', 'Haskell for Beginners', 7614411);
insert into `teachers` values (5899114, 'John Cartwright', '12345 ext 1212', 'BES-201');
insert into `modules` values ('MC1', 'Mathematics', 5899114);
insert into `teachers` values (7099543, 'Dave Moe', 'BES-205', '65432 ext 2121');
insert into `modules` values ('MC2', 'Advanced Mathematics', 7099543);
insert into `student` values
(156123,'Nuno Bloggs','[email protected]'),
(156897,'John Trump','[email protected]'),
(123987,'Lidia Elliott','[email protected]'),
(777123,'Alicia Smith','[email protected]'),
(127845,'Sophie Johns','[email protected]');
insert into `module_enrollment` values
(1,'HSB',156123),
(2,'HCI-101',156123),
(3,'HSB',156897),
(4,'MC1',156897),
(5,'MC2',156897),
(6,'MC2',777123),
(7,'HSB',127845),
(8,'HCI-101',127845),
(9,'MC1',127845),
(10,'MC2',127845);
select name from teachers;
select * from student;
select distinct id from student, module_enrollment
where student.id = module_enrollment.student_id and module_code = 'MC2';
-- Your results should not include duplicates or incorrect information.
select distinct id, name, email
from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'HCI-101';
select distinct s.name from student s left outer join module_enrollment me on s.id = me.student_id
where s.name not in (
select s.name from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'MC1'
)
select s.name, s.email from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'MC1'
and s.name in (
select s.name from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'MC2'
);
select s.name, s.email from student s, module_enrollment me1, module_enrollment me2
where s.id = me1.student_id and s.id = me2.student_id
and me1.module_code = 'MC1'
and me2.module_code = 'MC2'
select name, tel_no from teachers where office like 'BES%';
select id from module_enrollment where module_code in ('MC1', 'MC2');
select distinct s.name, s.email from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'MC2'
or s.name in (
select s.name from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'MC1'
);
select name, email from student where email not like '%gmail.com';
select distinct s.name, s.email from student s, module_enrollment me1, module_enrollment me2, module_enrollment me3
where s.id = me1.student_id and s.id = me2.student_id and s.id=me3.student_id
and me1.module_code = 'HSB'
and me2.module_code = 'MC2'
and me3.module_code = 'HCI-101'
select id, name from student where name like '%ia%';
select distinct s.name from student s left outer join module_enrollment me on s.id = me.student_id
where s.name not in (
select s.name from student s, module_enrollment me
where s.id = me.student_id and me.module_code = 'MC1' OR s.id = me.student_id and me.module_code = 'MC2' OR s.id = me.student_id and me.module_code = 'HCI-101'
)
drop table if exists cd, artist;
create table `artist` (
`artid` int primary key,
`artname` varchar(100)
);
insert into `artist` values
(6,'Animal Collective'),
(3,'Deadmau5'),
(7,'Kings of Leon'),
(4,'Mark Ronson'),
(5,'Mark Ronson & The Business Intl'),
(8,'Maroon 5'),
(2,'Mr Scruff'),
(1,'Muse');
create table `cd` (
`cdid` int primary key,
`artid` int,
`cdtitle` varchar(100),
`cdprice` double,
`cdgenre` varchar(50),
`cdnumtracks` int,
constraint fk_cd foreign key (`artid`) references `artist` (`artid`)
);
insert into `cd` values
(1,1,'Black Holes and Revelations',9.99,'Rock',NULL),
(2,1,'The Resistance',11.99,'Rock',NULL),
(3,2,'Ninja Tuna',9.99,'Electronica',NULL),
(4,3,'For Lack of a Better Name',9.99,'Electro House',NULL),
(5,4,'Version',12.99,'Pop',NULL),
(6,5,'Record Collection',11.99,'Alternative Rock',NULL),
(7,6,'Merriweather Post Pavilion',12.99,'Electronica',NULL),
(8,7,'7 Only By The Night',9.99,'Rock',NULL),
(9,7,'Come Around Sundown',12.99,'Rock',NULL),
(10,8,'Hands All Over',11.99,'Pop',NULL);
select cdtitle, cdprice from cd order by cdprice desc;
-- The Price of the CD should be returned in a column called ‘Full Price’ with tax (20%) included - the cd price in the database is not inclusive of tax.
select artname, cdtitle, (cdprice * 1.2) as `full price` from cd, artist where cd.artid = artist.artid;
-- then by price from the highest price to the lowest one.
select cdtitle, cdgenre, cdprice from cd order by cdgenre ASC, cdprice DESC;
select cdtitle as `Cheapest CD` from cd where cdprice <= all(select cdprice from cd);
select min(cdprice) as `Cheapest CD` from cd; -- in case you have a different understanding of this question.
-- The result should be presented in a column named ‘CD Price Range’.
select (max(cdprice) - min(cdprice)) as 'CD Price Range' from cd;
select (count(cdtitle)) as 'Count of $9.99 CD\'s' from cd where cdprice = 9.99;
select cdtitle from cd where cdprice >= all (select cdprice from cd where cdgenre = 'Electronica') and
####e. Find the number of different Prices in the CD table.
select count(distinct cdprice) from cd;
select * from cd, artist where cd.artid = artist.artid and cdprice <= all(select cdprice from cd);
-- Only return results for artists with more than one CD. The results should be in the following format:
-- || Artist | Average CD Price | Number of CD’s ||
select artist.artname as `Artist`, AVG(cdprice) as `Average CD price`, COUNT(cdid) as `Number of CDs`
from cd, artist where cd.artid = artist.artid group by artist.artname having `Number of CDs` > 1;
-- but not including ‘Electronica’ albums (you might like to use a WHERE in this one too).
-- The results should be in the following format:
-- || Artist | Average CD Price | Number of CD’s ||
select artist.artname as `Artist`, AVG(cdprice) as `Average CD price`, COUNT(cdid) as `Number of CDs`
from cd, artist where cd.artid = artist.artid and cdgenre <> 'Electronica' group by artist.artname;