sql语句查询一对一,一对多,多对多

mysql 专栏收录该内容
4 篇文章 0 订阅


//创建用户且置密码,在MySQL中行,但在Oracle中行  ----必须在超级管理员身份下操作
create user hncu identified by '1234'

DROP DATABASE mydb2; //删除数据库
//查询(显示数据库)
SHOW DATABASES; /*用Tab键补全代码,类似MyEclipse中的Alt+/ */

//创建数据库 并手动指定编码格式
//错,因为根据手册的查询,数据库名应该在 EXISTS后面
CREATE DATABASE hncu IF NOT EXISTS DEFAULT CHARACTER SET 'utf8';
//改正:
CREATE DATABASE IF NOT EXISTS hncu DEFAULT CHARACTER SET 'utf8';

//创建表格
CREATE TABLE stud(
  id INT PRIMARY KEY,
  sname VARCHAR(30) ,
  age INT);
 
 //往数据表中插入数据
 INSERT INTO stud VALUES( 1003,'Rose',22 );
 SELECT * FROM stud;
 
 USE hncu;
 SHOW TABLES;//查询(显示)表格
 DESC stud;  //查看数据表student的表结构
 
 SELECT sname,age FROM stud; //只查询(显示)表中的指定列
 
 DELETE FROM stud WHERE age=30; //删除年龄为30的表记录
 
 UPDATE stud SET sname='杰克' WHERE sname='Jack'; //更改数据
 
-----------------------------------------------------------------------
varchar(20)  ----可变的char数组,类似Java当中的String
char(20)   ----固定长度的char数组

//SQL语言 全部忽略大小写----大小写不敏感

//更改表结构ALTER TABLE (添加一列)
ALTER TABLE stud ADD COLUMN score NUMERIC(4,2);
INSERT INTO stud VALUES(1004,'张三',38,60);
INSERT INTO stud VALUES(1005,'王三',30,60);
INSERT INTO stud VALUES(1006,'王五',30,60);
INSERT INTO stud VALUES(1007,'王五六',30,80);
SELECT * FROM stud;
//※范围查询
//查询年龄在24-26之间的学生信息
//连续区间内的查询
SELECT * FROM stud WHERE age>=24 AND age<27;
//用BETWEEN是左右都包含,如下功能是[24,26]
SELECT * FROM stud WHERE age BETWEEN 24 AND 26;
//离散的多个
SELECT * FROM stud WHERE age=24 OR age=38;
SELECT * FROM stud WHERE age IN(24,26,30);

//※模糊查询LIKE  参数:%(任意匹配), _(匹配一个)
//查询姓“王”的学生信息
SELECT * FROM stud WHERE sname LIKE '王%'
//查询姓“王”且名为单字的学生信息
SELECT * FROM stud WHERE sname LIKE '王_';
//查询姓“王”且名为双字的学生信息
SELECT * FROM stud WHERE sname LIKE '王__';
//查询姓名中包含“五”字的学生信息
SELECT * FROM stud WHERE sname LIKE '%五%';

//※范围查询和模糊查询联合
//查询姓名中包含“五”字 且 年龄大于30 的学生信息
SELECT * FROM stud WHERE sname LIKE '%五%' AND age>30;

//查询
//查询无名英雄学生的信息(VARCHAR)
SELECT * FROM stud WHERE sname IS NULL;
//查询没有年龄信息的学生
//错:SELECT * FROM stud WHERE age==NULL;
SELECT * FROM stud WHERE age IS NULL;

//创建视图
CREATE VIEW studView AS SELECT * FROM stud WHERE score>=60;
SELECT * FROM studview;


//聚合函数
//统计表格的行数
SELECT COUNT(*) AS TEMPTABLE FROM stud;
SELECT COUNT(1) AS TEMPTABLE FROM stud;
//统计有年龄值的学生人数
SELECT COUNT(age) AS TEMPTABLE FROM stud;
//统计有年龄值且有分数值的学生人数
SELECT COUNT(age) AS TEMPTABLE FROM stud WHERE score IS NOT NULL;
//统计平均分且取整(AVG函数只统计非NULL的数据记录)
SELECT ROUND(AVG(score)) FROM stud; //这种方式一般不用,因为列名是自动生成的,我们在程序中不好访问
SELECT ROUND(AVG(score)) AS averageScore FROM stud; 
//分数求和
SELECT SUM(score) AS ss FROM stud; 
//年龄最大值
SELECT MAX(age) AS maxAge FROM stud;

//WHERE子句 IN子句
//查询年龄最小的那个人的名字
SELECT sname FROM stud WHERE age=(SELECT MIN(age) FROM stud);
SELECT sname FROM stud WHERE age IN(SELECT MIN(age) FROM stud);

//排序
SELECT * FROM stud GROUP BY age ASC; //不重复排序(即年龄相同的,只显示第一个0
SELECT * FROM stud GROUP BY age ASC; //显示出所有年龄段
SELECT * FROM stud ORDER BY age ASC; //普通排序--升序
SELECT * FROM stud ORDER BY age DESC; //普通排序--降序

SELECT DISTINCT sname,age FROM stud GROUP BY age DESC;

//EXISTS() 判断括号内的内容是否存在----注意,下面的例子,只要存在年龄为26的学生,就会输出所有数据
SELECT * FROM stud WHERE EXISTS( SELECT * FROM stud WHERE age=26 );

//演示分组
ALTER TABLE stud ADD COLUMN dept VARCHAR(20);
UPDATE stud SET dept='信息学院' WHERE score>=65;
UPDATE stud SET dept='通信学院' WHERE score=60;
UPDATE stud SET dept='土木学院' WHERE score<60;
SELECT * FROM stud;

//分组计算
//计算信息学院学生的平均分
SELECT AVG(score) FROM stud WHERE dept='信息学院'; 
//按学院计算平均分
SELECT dept,AVG(score) AS '学院平均分' FROM stud GROUP BY dept;

//插入记录,当数据不全时,要指定列名
INSERT INTO stud(id,sname,age,score) VALUES(1010,'李小明',25,90);

------------------------------------
数据库编码问题
方法1:可以在MySQL的配置文件如my.ini中指定:
  default-character-set = GBK  或
  default-character-set = utf8
方法2:在创建数据库时自己指定,如:
CREATE DATABASE IF NOT EXISTS hncu DEFAULT CHARACTER SET 'utf8';
▲相比较而言,对我们来讲,第2种方法更好。一是配置文件是平台,不能随意改,而且通常是由DBA来做的,我们没权设置,甚至MySQL都不在我们的电脑中。二是只要我们自己在创建数据库时自己指定编码,无论平台默认配置的是什么编码,对我们没有影响,一句话不依赖你的平台----可移置及兼容性好。

SHOW VARIABLES; //查询系统中的所有变量
SHOW VARIABLES WHERE variable_name LIKE 'character%'; //查询系统中所有的编码方面的参数
查询结果:
character_set_client utf8  //客户端编码 (不同的客户端显示的可能不一样,如cmd窗口和SQLyong)
character_set_connection  utf8  //客户端连接数据库时用的编码
character_set_database gbk  //数据库的默认编码(一般来讲,这是由my.ini配置文件定的。这是没进数据库时的通用编码)
character_set_filesystem binary  //这是数据库自己存储数据文件时用的编码,跟我们关系不大
character_set_results utf8  //查询之后的结果集的编码
character_set_server gbk  //MySQL数据库服务器自己的编码  iso8859-1在这里称Latin1
character_set_system  utf8
character_set_dir   MySQL安装目录 \share\charsets

对我们来讲,为了不出现乱码,必须保证client和connection的编码一致,否则就会乱码。
character_
set_database 数据库的编码必须要能够支持中文,否则输入中文有问题的

//如何设置指定的编码
set character_set_client=gbk;

SET character_set_client=gbk;
SHOW VARIABLES WHERE variable_name LIKE 'character%';
SELECT * FROM stud;//原来的数据显示正常
INSERT INTO stud VALUES(1011,'城院',20,88,'数计学院');
SELECT * FROM stud;//刚刚插入的那条记录,是乱码 //因为我们这里client是gbk,而connection是utf8,不一致了
SET character_set_connection=gbk;//已经把client和connection设成gbk,一致了
INSERT INTO stud VALUES(1012,'城院2',20,88,'数计学院');
SELECT * FROM stud;//显示刚刚插入的那条记录,还是乱码。因为数据库表stud的编码是utf8,而我们客户端与它的连接都是gbk

▲综上,client、connection、我们所访问的数据库的编码  这三者都要一致且应该是支持中文的编码
上面只能保证添加到数据库中的汉字不会出现乱码。
▲如果读取出来,还要看results、所访问的数据库的编码和我们java代码中的解码是否一致。

CREATE DATABASE IF NOT EXISTS aaa DEFAULT CHARACTER SET 'utf8';
DROP DATABASE aaa;

SHOW VARIABLES; //查询系统中的所有变量
SHOW VARIABLES WHERE variable_name LIKE 'character%'; //查询系统中所有的编码方面的参数

SET character_set_client=gbk;
SHOW VARIABLES WHERE variable_name LIKE 'character%';
SELECT * FROM stud;
INSERT INTO stud VALUES(1011,'城院',20,88,'数计学院');
SET character_set_connection=gbk;
INSERT INTO stud VALUES(1012,'城院2',20,88,'数计学院');
SELECT * FROM stud;

※SQL加强
DELETE FROM stud WHERE id>=1011;
//统计各个学院的平均分且排序
SELECT dept,AVG(score) FROM stud GROUP BY dept  ORDER BY AVG(score);


//字符串处理函数
SELECT * FROM stud WHERE sname='AAA';
SELECT * FROM stud WHERE TRIM(sname)='AAA';
SELECT * FROM stud WHERE LTRIM(RTRIM(sname))='AAA';//和上面等价
SELECT * FROM stud;

SHOW VARIABLES WHERE variable_name LIKE 'character%';
SET character_set_connection=utf8;
SET character_set_client=utf8;

UPDATE stud SET dept='数计学院' WHERE id=1011;

SELECT LEFT(TRIM(sname),2) FROM stud; //取去掉空格后的左起2个字符
SELECT REVERSE(TRIM(sname)) FROM stud;

CREATE TABLE person(
  id INT,
  sname VARCHAR(30) ,
  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,
  age INT
); //用NOT NULL 限制非空输入

SELECT * FROM TABLES;

//性别字段: 一般不定义成BOOLEAN型,因为有的数据库不支持,为考虑兼容,通常用CHAR(1)
CREATE TABLE a(
  id INT UNIQUE,
  sname VARCHAR(10),
  sex CHAR(1) DEFAULT '0'
);

INSERT INTO a VALUES(1,'Jack');  //错:未指定列名的方式赋值时,必须要给全,默认值不给也不行
INSERT INTO a VALUES(1,'Jack','0');//对
INSERT INTO a(id,sname) VALUES(1,'Tom'); //错:UNIQUE限定该列的值必须唯一(可以为NULL,但最多只能有一个)
INSERT INTO a(id,sname) VALUES(2,'Tom'); //对,性别未赋,则用默认
//性能优化:指定列名的方式性能更好!

//显示性别 (真实值与显示值之间的转换)
SELECT * FROM a;
SELECT id,sname,(CASE sex WHEN '0' THEN '女' WHEN '1' THEN '男' ELSE 'Null' END) xb FROM a; 
SELECT id,sname,(CASE sex WHEN '0' THEN '女' WHEN '1' THEN '男' ELSE 'Null' END) AS xb FROM a; 
SELECT id,sname,(CASE WHEN sex='0' THEN '女' WHEN sex='1' THEN '男' ELSE 'Null' END) AS xb FROM a;

//无关子查询
//需求:具有同龄人的学生
SELECT * FROM stud;
SELECT * FROM stud WHERE age IN ( SELECT age FROM stud GROUP BY age HAVING COUNT(age)>=2 ) ORDER BY age DESC;
//练练别名
SELECT * FROM stud AS xs WHERE age IN ( SELECT age FROM xs GROUP BY age HAVING COUNT(age)>=2 ) ORDER BY age DESC;

//需求2:不但具有同龄人,而且年龄大于等于30的学生
//法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;


//固定搭配
SELECT * FROM  +  WHERE  + ORDER BY(要放在最后)
GROUP BY + HAVING


-----------------------------------------
DROP TABLE person;

SELECT NAME, NAME

CREATE TABLE person(
   id INT,
   NAME VARCHAR(10),
   sex CHAR(1),
   wife INT,
   husband INT
);
INSERT INTO person VALUES(1,'小花','0',0,3);
INSERT INTO person VALUES(2,'玉芬','0',0,4);
INSERT INTO person VALUES(3,'张三','1',1,0);
INSERT INTO person VALUES(4,'李四','1',2,0);
INSERT INTO person VALUES(5,'王五','1',0,0);

//一对一关系的操作:查出每对夫妻的姓名
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 AND 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;

//一对多的关系  代码演示
//步骤1:画E-R图
//步骤2:分别建实体表,并给多方的表添加外键约束
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_fk FOREIGN KEY(pid) REFERENCES person2(id)
);
DROP TABLE car;

//步骤3:为两个表添加测试数据
//实体表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('C002','Benz',123.5,'P001');
INSERT INTO car(id,cname,price,pid) VALUES('C003','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.5,'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) 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 );

//查询哪些人没有车
SELECT * FROM person2 WHERE id NOT IN( SELECT pid FROM car );

//用左关联(LEFT JOIN)来查询:哪些人有什么样的车(没车的也是一种情况,要显示)
SELECT person2.pname,car.cname,car.price 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;


--------------------------------------------------
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 NUMERIC(5,2)
);

CREATE TABLE sj(
   studId VARCHAR(32) NOT NULL,
   jectId VARCHAR(32)
);


//建立联合主键
ALTER TABLE sj ADD CONSTRAINT sj_pk PRIMARY KEY(studId,jectId);
//添加外键约束1(为sj表的studId字段添加外键student(id)约束)
ALTER TABLE sj ADD CONSTRAINT sj_fk1 FOREIGN KEY(studId) REFERENCES student(id);
//添加外键约束2(为sj表的jectId字段添加外键ject(id)约束)
ALTER TABLE sj ADD CONSTRAINT sj_fk2 FOREIGN KEY(jectId) REFERENCES ject(id);

//添加测试数据
//学生表
INSERT INTO student(id,NAME,age) VALUES('S001','Jack',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(studId,jectId) VALUES('S001','J001');
INSERT INTO sj(studId,jectId) VALUES('S001','J002');
INSERT INTO sj(studId,jectId) VALUES('S001','J003');
INSERT INTO sj(studId,jectId) VALUES('S002','J001');
INSERT INTO sj(studId,jectId) VALUES('S002','J003');
INSERT INTO sj(studId,jectId) VALUES('S003','J001');
INSERT INTO sj(studId,jectId) VALUES('S003','J002');
INSERT INTO sj(studId,jectId) VALUES('S004','J003');
INSERT INTO sj(studId,jectId) VALUES('S005','J001');
SELECT * FROM sj;

应用测试
//查询哪些人选了哪些课 ----要求显示:人名,课程名
//采用的是92标准
SELECT student.name,ject.NAME FROM student,ject,sj WHERE student.id=sj.studId AND sj.jectId=ject.id;
//采用96标准
SELECT student.name,ject.NAME FROM student
       INNER JOIN sj ON student.id=sj.studId
       INNER JOIN ject ON sj.jectId=ject.id;

//查询哪些人没有选课(左关联)
SELECT student.name,ject.NAME FROM student
       LEFT JOIN sj ON student.id=sj.studId
       LEFT JOIN ject ON sj.jectId=ject.id WHERE ject.NAME IS NULL;

//查询哪些课没人选(右关联)
SELECT student.name,ject.NAME FROM student
       RIGHT JOIN sj ON student.id=sj.studId
       RIGHT JOIN ject ON sj.jectId=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.studId=student.id WHERE student.NAME IS NULL;


※存储过程

//定义存储过程p1 // “DELIMITER

”当作结束标志(否则默认是把“;“号当作结束标记),这样存储过程中的语句结束符";"就不会当作过程的结束标记。
DELIMITER
CREATEPROCEDUREp1()BEGINSELECTFROMstud;INSERTINTOstud(id,sname,age,score,dept)VALUES(1014,,33,55,);END

DELIMITER;   //把结束标记还原回来

CALL p1();  //调用存储过程p1

//带参数的存储过程
DELIMITER

CREATEPROCEDUREp2(INidINT,INnmVARCHAR(30))BEGININSERTINTOstud(id,sname)VALUES(id,nm);END

DELIMITER ;

DROP PROCEDURE p2;
CALL p2(1015,'吊丝');


//有返回值的存储过程----参数与变量问题( @变量名  ,一个@为用户变量,两个@即 @@为全局的系统变量 )
DELIMITER

CREATEPROCEDUREp3(INidINT,INnmVARCHAR(30),OUTnumINT)BEGININSERTINTOstud(id,sname)VALUES(id,nm);SELECTCOUNT()INTOnumFROMstud;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){
   rollback();
}


  • 1
    点赞
  • 1
    评论
  • 3
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值