1.login system user:
system/"password"
2.use user"sys" login:
connect sys/root as sysdba;
3.check current user:
show user;
4.select check data dictionary:
select username from dba_users;
select tablespace_name from dba_tablespaces;
5.enable user "scott":
alter user "username" account unlock;
6.login scott:
connect scott/tiger
7.unlock system:
sqlplus / as sysdba
SQL> alter user system account unlock;
8.look at the data dictionary:
desc dba_users;
desc dba_tablespaces;
desc user_constraints;
9.to create a permanent tablespace:
SQL> create tablespace test1_tablespace
datafile 'tempfile1.dbf' size 10m;
10.create temporary tablespace:
SQL> create temporary tablespace temptest1_tablespace
temfile 'tempfile1.dbf' size 10m;
11.look at the location of the permanent tablespace:
SQL>desc dba_data_files;
12.look at the location of the 'test1_tablespace':
SQL>select file_name from dba_data_file where tablespace_name='TEST1_TABLESPACE';
13.change the state of the tablespace:
SQL> alter tablespace test1_tablespace
online;
14.increase the tablespace
SQL> alter tablespace test1_tablespace
add datafile 'test2_file.dbf' size 10m;
15.look at tablespace:
SQL> select file_name from dba_data_file where tablespace_name='TEST1_TABLESPACE';
16.delete data file:
SQL> alter tablespace test1_tablespace
drop datafile 'test2_file.dbf';
17.delete table space:
SQL> drop tablespace test1_tablespace including contents;
18.create table
SQL> create table userinfo
(id number(6.0),
username varchar2(20),
userpwd varchar2(20),
email varchar2(30),
regdate date);
19.check table data
SQL> desc userinfo
20.add data
SQL> alter table userinfo
add remarks varchar2(500);
21.change table data
SQL> alter table userinfo
modify userpwd number(6.0);
22.delete table data
SQL> alter table userinfo
drop column remarks;
23.rename data
SQL> alter table userinfo
rename column email to new_email;
24.empty table data
SQL> truncate table new_info;
25.delete table
SQL> drop table new_info;
26.add content
SQL> insert into userinfo
27.check content
SQL> select userpwd,email from userinfo;
SQL> select from userinfo;
28.insert content
SQL> insert into userinfo(id,username,userpwd)
values(2,'yyy','123');
29.copy table content
SQL> create table userinfo_new
as
select from userinfo;
SQL> create table userinfo_new1
as
select id,username from userinfo;
SQL> insert into userinfo_new
select * from userinfo;
SQL> insert into userinfo_new(id,username)
select id,username from userinfo;
30. update table content
SQL> update userinfo
set userpwd='111',email='
[email protected]';
SQL> update userinfo
set passwd='yyy'
where username='1';
31. delete content
SQL> delete from userinfo
where username='yyy';
32.create a no null constraint
SQL> create table userinfo_p
(id number(6.0)
username varchar2(20) not null,
userpwd varchar2(20) not null);
33.alter constraint table space
SQL> alter table userinfo
modify username varchar2(20) not null;
SQL> alter table userinfo
modify username varchar2(20) null;
34.create primary constraint space
SQL> creat table userinfo_p
(id number(6.0) primary key,
username varchar2(20),
userpwd varchar2(20));
SQL> create table userinfo_p1
(id number(6.0),
username varchar2(20),
userpwd varchar2(20),
constraint pk_id_username primary key(id,username));
35.find constraint
SQL> select constraint_name from user_constraints where table_name='USERINFO_P1';
36.add primary key
SQL> alter table userinfo
add constraint pk_id primaty key(id);
37.find primary key infomation
SQL> select constraint_name from user_constraints where table_name='USERINFO';
38.rename promary key
SQL> alter table userinfo
rename constraint pk_id to new_pk_id;
39.disable/enable primary key
SQL> alter table userinfo
disable constraint new_pk_id;
(enable)
40.check primary key status
SQL> select constraint_name,status from user_constraints where table_name= 'USERINFO';
41.delect constraint
SQL> alter table userinfo
drop constraint new_pk_id;
SQL> alter table userinfo
drop primary key;
42.setup key constraint when creat table
(from the table of the corresponding foreign key value must be inside the main table or a null value)
main table:
SQL> alter table typeinfo
rename column type to typeid;
slave table:
SQL> create table userinfo_f
(id varchar2(10) primary key,
username varchar2(20),
typeid_new varchar2(10) references typeinfo(typeid));
the main table value:
SQL> insert into userinfo_f(id,typeid_new);
values (1,1);
null value:
SQL> insert into userinfo_f(id,typeid_new)
values(2,null);
43.adding foreign key constraints when creat a table
SQL> creat table userinfo_f3
(id varchar2(10) primary key,
username varchar2(20),
typeid_new varchar2(10),
constraint fk_typeid_new1 foreign key(typeid_new) references typeinfo(typeid) on delete cascade);
44.adding foreign key when modify table
SQL> alter table userinfo_f4
add constraint fk_typeid_alter foreign key(typeid_new) references typeinfo(typeid);
45.disble/enable foreign key
SQL> alter table userinfo_f4
disable constraint Fk_TYPEID_ALTER;
46.delete foreign key
SQL> alter table userinfo_f4
drop constraint FK_TYPEID_ALTER;
47.setup unique constraint when creat table
SQL> create table userinfo_u
(id varchar2(20) primary key,
username varchar2(20) unique,
userpwd varchar2(20));
SQL> create table userinfo_u1
(id varchar2(20) primary key,
username varchar2(20),
constraint un_username unique(username));
48.adding unique constraint when modify table
SQL> alter table userinfo_u2
add constraint un_username_new unique(username);
49.diable unique constraint
SQL> alter table userinfo_u2
diable constraint UN_USERNAME_NEW;
50.delete unique constraint
SQL> alter table userinfo_u2
drop constraint UN_USERNAME_NEW;
51.setup check constraint when create table
SQL> create table userinfo_c
(id varchar2(10) primary key,
username varchar2(20),
salary number(5,0) check(salary>0));
SQL> create table userinfo_c1
(id varchar2(10) primary key,
username varchar2(20),
salary number(5,0),
constraint ck_salary check(salary>0));
52.adding check constraint when modify table
SQL> alter table userinfo_c3
add constraint ck_salary_new check(salary>0));
53.disable check constraint
SQL> alter table userinfo_c3
diable constraint CK_SALARY_NEW;
54.drop check constraint
SQL> alter table userinfo_c3
drop constraint CK_SALARY_NEW;
55.setup alias
SQL> col username heading "username";
SQL> select id as "id",username as "username",salary "salary" from users; (the avaliable spaces instead of)
56.setup check constraint when create table
column level:
SQL> create table userinfo_c
(id varchar2(10) primary key,
username varchar2(20),
salary number(5,0) check(salary>0));
table level:
SQL> create table userinfo_c1
(id varchar2(10) primary key,
username varchar2(20),
salary number(5,0),
constraint ck_salary check(salary>0));
57.don“t show the same user name
SQL> select distinct username as "username" from users;
58.with conditions of the query
SQL> select username from users where salary>800;
SQL> select username,salary from users where id='3';
SQL> select username from users where salary>800 and salary <> 1800.5; (<> unequal)
SQL> select from users where username='aaa' or salary>2000;
SQL> select from users where username='aaa' or (salay>800 and salary<=2000);
SQL> select from users where not(username='aaa');
59. the priority of the logical operators
1.not
2.and
3.or
60.
fuzzy query : ”_“represents a character ”%“ represents characters
SQL> select from users where username like 'a%';
SQL> select from users where username like '_a%';
SQL> select from users where username like '%a%';
61.range query
SQL> select from users where salary between 800 and 2000;
SQL> select from users where salary not between 800 and 2000;
SQL> select from users where username in ('aaa','bbb');
SQL> select from users where username not in ('aaa','bbb');
62.to sort the results of the query (desc↑ asc↓)
SQL> select from users order by id desc;
SQL> select from users order by id desc,salary asc;
63.using the operator/funtion to change the query results
1-SQL> select id,username,salary+200 from users;
2-case...when
SQL> select username,case username when 'aaa' then 'computer department'
when 'bbb' then 'marketing department' else 'other department' end as department
from users;
SQL> select username,case when salary<800 then 'salary low'
when salary>5000 then 'salary high' end as salarylevel
from users;
3-decode funtion use
SQL> select username,decode(username,'aaa','computer department','bbb','marketing department','other')
as department from users;
#########SQL statement#############
1.create user
//create user with password, and run in MYSQL, but in Oracle must be operating under the super administrator
create user hncu indentified by '1234'
2.create database
//create database and manually specify the encoding format
//wrong, because according to the manual of the query, the database name should be behind the EXISTS
CREATE DATABASE hncu IF NOT EXISTS DEFAULT CHARACTER SET 'utf8';
//correct
CREATE DATABASE IF NOT EXISTS hncu DEFAULT CHARACTER SET 'utf8';
3.delete database
DROP DATABASE mysql2;
//search(show database)
SHOW DATABASES
二.database encoding issue
1.specify the database code
a. can in the MySQL configuration file, such as my.ini is specified
default-character-set = GBK or
default-character-set = utf8
b. their designated when creating the database, ex:
CREATE DATABASE IF NOT EXISTS hncu DEFAULT CHARACTER SET 'utf8';
2.check database encoding
SHOW VARIABLES; //query system all variable
SHOW VARIABLES WHERE variable_name LIKE 'character%'; //query system all encoding parameters
the query results:
character_set_client utf8 //client encoding
character_set_connection utf8 //the encoding are used when the client connect to the database
character_set_database gbk //the default encoding for the database (my.ini)
character_set_filesystem binary //this is a database to store data files with encoding, has little to do with us
character_set_results utf8 //after the query result encoding
character_set_server gbk //the MYSQL database server here own encoding iso8859-1 Latin1 said
character_set_system utf8
character_set_dir MY_SQL installation directory \share\charsets
//for use, in order not to appear garbled, must ensure that the client and the connection of coding
is consistent, otherwise it will be garbled. character set the database code must be able to
support chinese, otherwise there is something wrong with the type in chinese.
3.setup(modify) encoding
//how to set up the specified code
set character_set_client=gbk;
SET character_set_client=gbk;
SHOW VARIABLES WHERE variable_name LIKE 'character%';
SELECT * FROM studl; //the original data display is normal
INSERT INTO stud VARLUES(1011,'城院',20,88'数计学院');
SELECT FROM stud; //just insert the record is garbled, because our client here is GBK,and the connection is utf8,inconsistent
SET character_set_connection=gbk;//have client and connection set GBK,consistent
INSERT INTO stud VARLUES(1011,'城院',20,88'数计学院');
SELECT * FROM stud;//show just insert the recode is garbled, because the stud is encoding utf8 database table, and our client and its connectin is GBK
//bring in conclusion, the client, the connection, we have access to the database code ,All three are consistent
//and should be to support Chinese coding, the above guarantee added to the database of Chinese character not garbled works.
//bring in read out, also want to see the results, the database access by encoding anddecoding are consistent in our java code
三. create table
//create table
CREATE TABLE stud(
id INT PRIMARY KEY,
sname VARCHAR(30),
age INT);
varchar(20) ---variable char array, similar to the string in Java
char(20) --- the char array of fixed length
//SQL language ignore case - all case-insenstive
四.operation to form
USE hncu;
SHOW TABLES; //query (display) form
DESC stud; //view the data student table structure
1.inset data to the data table
INSERT INTO stud VALUES(1003,'Rose',22);
//insert recodes, when the data is not full-time, to specify the column name
INSERT INTO stud(id,sname,age,score) VALUES(1010,'lixiaoming',25,90);
//NOt specified column name assignment, must give full, default values are not give
INSERT INTO a(id,sname) VALUES(1,'Tim');//wrong,UNIQU limit value in the column must be uniqu(can be NULL,but there can be at most one)
INSERT INTO a(id,sname) VALUES(2,'Tom'); //right, gender did not assign, by default
//performance optimization, performance of the specified column name way better!
2.query data
SELECT * FROM stud;//query all data from table
SELECT sname,age FROM stud; //only query (show) the special column in the table
3.delect data
DELECT FROM stud WHERE age=30;//delect the age of 30 table record
4.update data
UPDATE stud SET sname='jieke' WHERE sname='Jack';
5.change the table structure(add column)
ALTER TABLE stud ADD COLUMN scroe NUMERIC(4,2);
######set up joint primary key######
ALTER TABLE sj ADD CONSTRAINT sj_pk PRIMARY KEY(studid,jectid);
//add 1 foreign key constraint(for sj table jectid field to add a foreign key student(id) constraints)
ALTER TABLE sj ADD CONSTRAINT sj_pk1 FOREIGN KEY(studid) REFERENCE student(id);
//add foreign constraint2(for sj table jectid field to add a foreign key ject(id) constraint)
ALTER TABLE sj ADD CONSTRAINT sj_pk2 FOREIGN KEY(jectid) REFERENCE ject(id);
6.create view
CREATE VIEW studView AS SELECT FROM stud WHERE score>=60;
SELECT FROM studview;
五.those things on the table query operation
INSERT INTO stud VALUES(1004,'zhangsan',38,60);
INSERT INTO stud VALUES(1004,'wangsan',30,60);
INSERT INTO stud VALUES(1004,'wangwu',30,60);
INSERT INTO stud VALUES(1004,'wangwuliu',30,80);
range query
//query the student infomation between the range ages of 24 and 26
1)continuous range query
SELECT FROM stud WHERE age>=24 AND age<27;
2)use is BETWEEN left and right sides are included, the following function is [24,26]
SELECT FROM stud WHERE age BETWEEN 24 AND 26;
3)discrete multiple
SELECT FROM stud WHERE age=24 or age=38;
SELECT FROM stud WHERE age IN (24,26,30);
fuzz query parameters LIKE: %(arbitrary),(a match)
//query name begin "wang" of students
SELECT FROM stud WHERE sname LIKE 'wang%';
//query name 'wang'(single)
SELECT FROM stud WHERE sname LIKE 'wang';
//query name 'wang'(double)
SELECT FROM stud WHERE sname LIKE 'wang_';
//query name include 'wu'
SELECT FROM stud WHERE sname LIKE '%wu%';
fuzz and range qurey
//query name include begin 'wang' and the age of more than 30 students
SELECT * FROM stud WHERE sname LIKE '%wang%' and age>30;
a null value query
//query unsung hero student information (VARCHAR)
SELECT FROM stud WHERE sname IS NULL;
//query no age infomation of students
SELECT FROM stud WHERE age==NULL //error
SELECT FROM stud WHERE age IS NULL;
aggregation funtion
1)COUNT statistical table rows
SELECT COUNT(*) AS TEMPTABLE FROM stud; //AS TEMPTABLE: is to check the results (table rows) anthor named:temptable
SELECT COUNT(1) AS TEMPTABLE FROM stud;
//the number of students in statistical have age values
SELECT COUNT(age) AS TEMPTABLE FROM stud;
//count the number of students in age value and score
SELECT COUNT(age) AS TEMPTABLE FROM stud WHERE score IS NOT NULL;
2)AVG statistical average and integer (note: AVG funtion only statistical not NULL data records)
SELECT ROUND(AVG(score)) FROM stud; //generally don`t use this way, because the column names are automatically generated, we are in the program is bad.
SELECT ROUND(AVG(score)) AS averageScore FROM stud;
3)SUM score sum
SELECT SUM(score) AS ss FROM stud;
4)MAX the maximum age
SELECT MAC(score) AS macAge FROM stud;
6.WHERE clause + IN clause
//query the youngest the person`s name
SELECT sname FROM stud WHERE age=(SELECT MIN(age) FROM stud);
SELECT sname FROM stud WHERE age IN(SELECT MIN(age) FROM stud);
7.sort
SELECT FROM stud ORDER BY age ASC; //don`t repeat orther(for the same age, just show the first)
SELECT FROM stud ORDER BY age ASC; //show all ages
SELECT FROM stud ORDER BY age ASC; // down ↑
SELECT FROM stud ORDER BY age DESC; // up ↓
8.distinct(do not duplicate values)
SELECT DISTINCT sname,age FROM stud GROUP BY age DESC;
9. EXISTS() whether the content of the brackets --note that the following example, as long as there is a age of 26 students, will output all the data
SELECT FROM stud WHERE EXISTS(SELECT FROM stud WHERE age=26);
10.demonstrate group
ALTER TABLE stud ADD COLUMN dept VARCHAR(20);
UPDATE stud SET dept='InformationSchool' WHERE score>=65;
UPDATE stud SET dept='CommunicationSchool' WHERE score=60;
UPDATE stud SET dept='CivilSchool' WHERE score<60;
//grouping calculation
//calculation at college average (average score for each of the students)
SELECT dept.AVG(score) AS 'SchoolAverageScore' FROM stud GROUP BY dept;
11.the string handling function
SELECT FROM stud WHERE sname='AAA';
SELECT FROM stud WHERE TRIM(sname)='AAA'; //remove the space around
SELECT * FROM stud WHERE LTRIM(RTRIM(sname))='AAA'; //same as above
UPDATE stud SET dept='MathSchool' WHERE id=1011;
SELECT LEFT(TRIM(sname),2) FROM stud; //take after remove the spaces from the left of the two chatacters
SELECT REVERSE(TRIM(sname)) FROM stud; // return a string inverted sequence of chatacters
CREATE TABLE person(
id INT,
sname VARCH(20),
age INT
);
ALTER TABLE person ADD CONSTRAINT person_pk PRIMARY KEY(id);
DROP TABLE person;
CREATE TABLE person(
id INT PRIMARY KEY,
sname VARCHAR(30) NOT NULL, // set the not null constraint
age INT
);
12.gender field(for example: data inventory of 0,1 and display for male and female)
//does not define a BOOLEAN type, because some database does not support, to consider the compatibility, usually CHAR(1)
CREATE TABLE a(
id INT UNIQUE
sname VARCHAR(10),
sex CHAR(1) DEFAULT '0'
);
//show sex(the real value show and transformation between the display value)
SELECT * FROM a;
SELECT id,sname,(CASE sex WHEN'0' THEN'female' WHEN '1' THEN 'male' ELSE 'Null' END) xb FROM a;
SELECT id,sname,(CASE sex WHEN'0' THEN'female' WHEN '1' THEN 'male' ELSE 'Null' END) AS xb FROM a;
SELECT id,sname,(CASE sex='0' THEN 'female' WHEN sex='1' THEN 'male' ELSE 'Null' END) AS xb FROM a;
13.uncorrelated subquery
//requirements:students with their same age peers
SELECT FROM stud;
SELECT FROM stud WHERE age IN (SELECT age FROM stud GROUP BY age HAVING COUNT(age)>=2)
ORDER BY age DESC;
//alias
SELECT FROM stud AS xs WHERE age IN(SElECT age FROM stud GROUP BY age HAVING COUNT(age)>=2)
ORDER BY ge DESC;
//requirements: not only is of the same age, and age greater than or equal to 30 students
//1)
SELECT FROM stud WHERE age IN (SELECT age FROM stud GROUP BY age HAVING COUNT(age)>=2 AND age>=30)
ORDER BY age DESC;
//2)
SELECT * FROM stud WHERE age>=30 AND age IN (SELECT age FROM stud GROUP BY age HAVING COUNT(age)>=2)
ORDER BY age DESC;
14.fixed colocation
SELECT * FROM + WHERE + ORDER BY (put in the last)
GROUP BY + HAVING
15.relational query
DROP TABLE person;
CREATE TABLE person(
id INT,
NAME VARCHAR(10),
sex CHAR(1),
wife INT,
husband INT
);
INSERT INTO person VALUES(1,'xiaohua','0',0,3);
INSERT INTO person VALUES(2,'yvfeng','0',0,4);
INSERT INTO person VALUES(3,'zhangsan','1',1,0);
INSERT INTO person VALUES(4,'lisi','1',2,0);
INSERT INTO person VALUES(5,'wangwu','1',0,0);
1)the operation of the one-by-one relationship: find out the name of each couple
一对一的操作:查出每对夫妻的姓名
CREATE VIEW w AS SELECT FROM person WHERE sex='0';
CREATE VIEW m AS SELECT FROM person WHERE sex='1';
//不利用表与表之间的关系
SELECT w.NAME AS 妻子,m.NAME AS 丈夫 FROM w,m WHERE w.husband=m.id m.wife=w.id;
//现在更先进的方式:利用表间的关系
SELECT w.NAME AS 妻子, m.NAME AS 丈夫 FROM w INNER JOIN m ON w.husband=m.id AND m.wife=w.id;
SELECT * FROM person;
2)一对多的关系 代码演示
//A:画E-R图
//B: 分别建实体表,并给多方的表添加外键约束
CREATE TABLE person2(
id VARCHAR(32) PRIMARY KEY,
pname VARCHAR(30),
sex CHAR(1)
);
CREATE TABLE car(
id VARCHAR(32) PRIMARY KEY;
cname VARCHAR(30),
price NUMERIC(10,2),
pid VARCHAR(32),
CONSTRAINT car_flk FOREIGN KEY(pid) REFERENCES person2(id)
);
DROP TABLE car;
//C:为两个表添加测试数据
//实体表1
INSERT INTO person2(id,pname,sex) VALUES('P001','Jack',1);
INSERT INTO person2(id,pname,sex) VALUES('P002','Tom',1);
INSERT INTO person2(id,pname,sex) VALUES('P003','Rose',0);
INSERT INTO person2(id,pname,sex) VALUES('P004','Mary',0);
INSERT INTO person2(id,pname,sex) VALUES('P005','Mike',1);
SELECT * FROM person2;
//实体表2
INSERT INTO car(id,cname,price,pid) VALUES('C001','BMW',123.5,'P001');
INSERT INTO car(id,cname,price,pid) VALUES('C001','Benz',123.5,'P001');
INSERT INTO car(id,cname,price,pid) VALUES('C001','BMW',223.5,'P001');
INSERT INTO car(id,cname,price,pid) VALUES('C011','BMW',83.5,'P003');
INSERT INTO car(id,cname,price,pid) VALUES('C012','Benz',100,'P003');
INSERT INTO car(id,cname,price,pid) VALUES('C013','Audi',223.5,'P003');
INSERT INTO car(id,cname,price,pid) VALUES('C021','BMW',88,'P004');
INSERT INTO car(id,cname,price,pid) VALUES('C022','QQ',10,'P004');
INSERT INTO car(id,cname,price,pid) VALUES('C023','Audi',73,'P005');
INSERT INTO car(id,cname,price,pid) VALUES('C033','Audi',1000);
//该句代码执行错误,因为编号为P006的人在person2表中不存在,这就是参照完整性
INSERT INTO car(id,cname,price,pid) VALUES('C033','Audi',1000,'P006');
SELECT * FROM car;
//查询:哪些人用什么车(用‘表名.列名’的形式访问列,如果列名不重复,可以省略表名)
//利用一方的主键和‘多方’的外键进行关联
SELECT person2.pname,car.cname FROM person2,car WHERE person2.id=car.pid;
//查询Jack有什么车
SELECT person2.pname,car.cname FROM person2,car WHERE person2.id=car.pid AND person2.pname='Jack';
//查询哪些人有两辆车以上
SELECT person2.pname,COUNT(pname) AS 车数量 FROM person2,car WHERE person2.id=car.pid GROUP BY pname
HAVING COUNT(pname)>=2 ORDER BY 车数量;
SELECT * FROM person2 WHERE id IN(SELECT pid FROM car GROUP BY pid HAVING COUNT(pid)>=2);
16.关联查询
//查询哪些人没有车
SELECT * FROM person2 WHERE id NOT IN(SELECT pid FROM car);
//用左关联(LEFT JOIN)来查询;哪些人用什么样的车(没车的也一样情况,要显示)
SELECT person2.pname,car.cname,car.pricee FROM person2 LEFT JOIN car ON person2.id=car.pid ORDER BY person2.id;
//用内关联(INNER JOIN)来查询:哪些人有什么样的车(没车的不显示)
SELECT person2.pname,car.cname,car.price FROM person2 INNER JOIN car ON person2.id=car.pid ORDER BY person2.id;
//查询每辆车的销售状况(如果有主人就显示,没有就NULL)
SELECT person2.pname,car.cname,car.price FROM person2 RIGHT JOIN car ON person2.id=car.pid ORDER BY person2.id;
(+在左边时 右关联, +在右边时,左关联)
//left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录
//right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
//inner join(等值连接) 只返回两个表中联结字段相等的行
DELETE FROM person2 WHERE id='P005';
CREATE TABLE student(
id VARCHAR(32) PRIMARY KEY,
NAME VARCHAR(30),
age INT
);
CREATE TABLE ject(
id VARCHAR(32) PRIMARY KEY,
NAME VARCHAR(30),
price NUMBER(5,2)
);
CREATE TABLE sj(
studld VARCHAR(32) NOT NULL,
jectld VARCHAR(32)
);
//建立联合主键
ALTER TABLE sj ADD CONSTRAINT sj_pk PRIMARY KEY(studld,jectld);
//添加外键约束1(为sj表的studld字段添加外键student(id)约束)
ALTER TABLE sj ADD CONSTRAINT sj_pk1 FOREIGN KEY(studld) REFERENCES ject(id);
//添加外键约束2(为sj表的jectld字段添加外键ject(id)约束)
ALTER TABLE sj ADD CONSTRAINT sj_fk2 FOREIGN KEY(jectld) REFERENCES ject(id);
//添加测试数据
//学生表
INSERT INTO student(id,NAME,age) VALUES('S001','jeck',25);
INSERT INTO student(id,NAME,age) VALUES('S002','Tom',24);
INSERT INTO student(id,NAME,age) VALUES('S003','张三',23);
INSERT INTO student(id,NAME,age) VALUES('S004','李四',24);
INSERT INTO student(id,NAME,age) VALUES('S005','Rose',25);
SELECT * FROM student;
//课程表
INSERT INTO ject(id,NAME,price) VALUES('J001','Java',25);
INSERT INTO ject(id,NAME,price) VALUES('J002','MySQL',30);
INSERT INTO ject(id,NAME,price) VALUES('J003','Oracle',55.9);
INSERT INTO ject(id,NAME,price) VALUES('J004','软件工程',20.25);
INSERT INTO ject(id,NAME,price) VALUES('J005','WEB开发',125);
SELECT * FROM ject;
//选课表
INSERT INTO sj(studld,jectld) VALUES('S001','J001');
INSERT INTO sj(studld,jectld) VALUES('S001','J002');
INSERT INTO sj(studld,jectld) VALUES('S001','J003');
INSERT INTO sj(studld,jectld) VALUES('S002','J001');
INSERT INTO sj(studld,jectld) VALUES('S002','J003');
INSERT INTO sj(studld,jectld) VALUES('S003','J001');
INSERT INTO sj(studld,jectld) VALUES('S003','J002');
INSERT INTO sj(studld,jectld) VALUES('S004','J003');
INSERT INTO sj(studld,jectld) VALUES('S005','J001');
SELECT * FROM sj;
应用测试
//查询哪些人选了哪些课--要求显示:人名,课程表
//采用的是92标准
SELECT student.name,ject.name FROM student,ject,sj WHERE student.id=sj.studld AND sj.jectld=ject.id;
//采用96标准
SELECT student.name,ject.NAME FROM student
INNER JOIN sj ON student.id=sj.studld
INNER JOIN ject ON sj.jectld=ject.id;
//查询哪些人没有选课(左关联)
SELECT sutdent.name,ject.NAME FROM student
LEFT JOIN sj ON student.id=sj.studld
LEFT JOIN ject ON sj.jectld=ject.id WHERE ject.NAME IS NULL;
//查询哪些课没有人选(右关联)
SELECT student.name,ject.NAME FROM student
RIGHT JOIN sj ON student.id=sj.studld
RIGHT JOIN ject ON sj.jectld=ject.id WHERE student.NAME IS NULL;
//左右关联可以互相转换,如把上面的代码用左关联
SELECT student.name,ject.NAME FROM ject
LEFT JOIN sj ON ject.id=sj.jectid
LEFT JOIN student ON sj.studld=student.id WHERE student.NAME IS NULL
六.存储过程
//定义存储过程p1 //"DELIMITER
"这句话是为了让解析器把"
"当做结束标志
(否则默认是把“;”当做结束标志),这样存储过程中的语句结束符';'就不会当做结束标志
DELIMITER$$
CREATE PROCEDURE p1()
BEGIN
SELECT * FROM stud;
INSERT INTO sutd(id,sname,age,score,dept) VALUE(1014,'刘三丰',33,55,'通信学院');
END$$
DELIMITER; //把结束标记还原回来
CALL p1();//调用存储过程p1
1.带参数的存储过程
DELIMITER$$
CREATE PROCEDURE p2(IN id INT, IN nm VARCHAR(30))
BEGIN
INSERT INTO stud(id,sname) VALUE(id,nm);
END$$
DELIMITER;
//存储过程参数类型(in,out,inout)
//in:跟C语言的函数参数的值传递类似,MySQL存储过程内部可能会修改此参数,
但对in类型参数的修改,对调用者(caller)是不可见的(not visible)
//out:从存储内部传值给调用者。在存储过程内部,该参数初始值为null,无论调用者是否给存储过程参数设置值
//inout:跟out类似,都可以从存储过程内部传值给调用者,不同的是调用者可以通过inout参数传值给存储过程
CALL p2(1015,'屌丝');
DROP PROCEDURE p2;
2.有返回值的存储过程-参数与变量问题(@变量名,一个@为用户变量,两个@即@@为全局的系统变量)
DELIMITER$$
CREATE PROCEDURE p3(IN id INT,IN nm VARCHAR(30), OUT num INT)
DEGIN
INSERT INTO stud(id,sname) VALUE(id,nm);
SELECT COUNT(*) INTO num FROM stud;
END$$
DELIMITER;
CALL p3(1016,'无名',@aa);
SELECT @aa; //输出变量aa的值
七.事务处理
START TRANSACTION
DELETE FROM stud WHERE id=1015;
DELETE FROM stud WHERE id=1014;
SELECT * FROM stud;
ROLLBACK / COMMIT; //滚回事务&提交事务
采用事务的java编程
try{
st.execute("START TRANSACTION;");
st.execute("DELETE FROM stud WHERE id=1015;");
st.execute("DELETE FROM stud WHERE id=1014;");
......
st.execute("commit();");
}catch(Exception e){
rollbask();
}