第四天,表与表之间的关系,一对多,多对多,查询

时间:2023-01-24 14:21:12

※MySQL中的字符编码(注意,utf8中没有'-',跟Java中不一样)
SHOW VARIABLES; //查看系统变量
//查询字符编码相关的系统变量
SHOW VARIABLES WHERE variable_name LIKE 'character%';

解决MySQK的中文乱码:
character_set_client,character_set_connection和character_set_results这三者必须一致(GBK,GB2312,UTF8这三者都可以,但若采用其中一种则3个变量都要设这种)

设置字符编码的系统变量:
set character_set_client=utf8; //独立设置某个变量
set names utf8; //同时设置3个:client、 connection和results

※其实,MySQL中的数据库、数据表 甚至 数据列 都可以有自己的编码,只是我们一般不专门设置。---从SQLyog中的更改表结构中可以查看出

INSERT INTO stud VALUES(4,'湖南',20);

CREATE TABLE person(
id INT,
NAME VARCHAR(30),
age INT
);

CREATE TABLE car(
id INT PRIMARY KEY, //不允许重复,也不允许NULL
NAME VARCHAR(30),
NO INT UNIQUE //不允许重复,允许NULL但最多只能一个
);
//除了在创建表时如上的方式直接指定主键,也可以通过修改表的方式单独创建主键:
ALTER TABLE person ADD CONSTRAINT person_pk PRIMARY KEY(id);
ALTER TABLE person ADD CONSTRAINT UNIQUE (NAME); //为name字段添加一个unique约束

//添加和删除unique约束 --通过约束名称
ALTER TABLE person ADD CONSTRAINT UNIQUE uniq_nm (NAME);
DROP INDEX uniq_nm ON person;


//删除主键
ALTER TABLE person DROP PRIMARY KEY;


//有关性别字段,比较好的表结构。DATE类型勉强用,建议不要用DATETIME。为考虑兼容性,最好用CHAR(19),VARCHAR(19) //datetime格式: 2016-11-11 23:24:09
CREATE TABLE s(
id INT,
sex CHAR(1) DEFAULT '0',
birth DATE
);
INSERT INTO s(id,birth) VALUES(3,'2008/8/8'); //因为sex字段设了default,所以该字段不手动赋值时,由默认值0来赋
按理,date的规范格式是"yyyy-MM-dd",但我们给其他格式如"yyyy/M/d"时,MySQL也会帮我们自动转换成规范格式。


//有关性别字段的显示
学习一个SQL语法: 手册-->函数和操作符-->控制流程函数-->Case-When

SELECT id, (CASE sex WHEN '0' THEN '女' WHEN '1' THEN '男' ELSE '其它' END) AS 性别, birth FROM s;


※1无关子查询
需求:查询具有同龄人的学生
SELECT * FROM stud WHERE age IN(20,22,23); //过渡版:"20,22,23" 写死了
SELECT age FROM stud GROUP BY age HAVING COUNT(age)>=2; //这句可以动态输出:20,22,23
综上:
SELECT * FROM stud WHERE age IN( SELECT age FROM stud GROUP BY age HAVING COUNT(age)>=2 ) ORDER BY age ASC;


//------------------
※2相关子查询(子查询中用到了外面的查询结果表)
需求:查询具有同龄人且年龄大于22的学生
SELECT * FROM stud as s2 WHERE age IN( SELECT age FROM stud where s2.age>22 GROUP BY age HAVING COUNT(age)>=2 ) ORDER BY age ASC;

select ... from ... where ... in( 子查询 ) order by ... asc(desc)
select ... from ... where ... group by ... having ...


※表与表之间的关系(1对1)
1、
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);


SELECT * FROM person WHERE sex='0';
SELECT * FROM person WHERE sex='1';

CREATE VIEW w AS SELECT * FROM person WHERE sex='0';
CREATE VIEW m AS SELECT * FROM person WHERE sex='1';

CREATE VIEW w2 AS SELECT id,NAME,sex,husband FROM person WHERE sex='0';
CREATE VIEW m2 AS SELECT id,NAME,sex,wife FROM person WHERE sex='1';


SELECT w.name AS wn, m.name AS mn FROM w INNER JOIN m ON w.husband=m.id AND m.wife=w.id;

SELECT * FROM w INNER JOIN m ON w.husband=m.id AND m.wife=w.id;