MySQL基础05
4.4联表查询
JOIN 对比
SELECT * FROM student
SELECT * FROM result
SELECT s.studentno,studentname,subjectno,studentresult
FROM student AS s
INNER JOIN result AS r
WHERE s.studentno=r.studentno
SELECT s.studentno,studentname,subjectno,studentresult
FROM student s
RIGHT JOIN result r
ON s.studentno=r.studentno
SELECT s.studentno,studentname,subjectno,studentresult
FROM student s
LEFT JOIN result r
ON s.studentno=r.studentno
操作 | 描述 |
---|
inner join | 如果表中至少有一个匹配,就返回行 | left join | 也会从左表中返回所有的值,即使右表中没有匹配 | right join | 也会从右表中返回所有的值,即使左表中没有匹配 |
– join (连接的表) on (判断的条件) 连接查询
– where 等值查询
SELECT s.studentno,studentname,subjectno,studentresult
FROM student s
LEFT JOIN result r
ON s.studentno=r.studentno
WHERE studentresult IS NULL
SELECT s.studentno,studentname,subjectname,studentresult
FROM student s
RIGHT JOIN result r
ON r.studentno=s.studentno
INNER JOIN `subject` sub
ON r.subjectno=sub.subjectno
自连接
自己的表和自己的表连接,核心:一张表拆成两张一样的表即可
父类
categoryid | categoryname |
---|
2 | 信息技术 | 3 | 软件开发 | 5 | 美术设计 |
子类
pid | categoryid | categoryname |
---|
3 | 4 | 数据库(软件开发) | 3 | 6 | web开发(软件开发) | 5 | 7 | PS技术(美术设计) | 2 | 8 | 办公信息(信息技术) |
操作:查询父类对应的子类关系
父类 | 子类 |
---|
信息技术 | 办公信息 | 软件开发 | 数据库、web开发 | 美术设计 | PS技术 | | |
CREATE TABLE `category`(
`categoryid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主题id',
`pid` INT(10) NOT NULL COMMENT '父id',
`categoryname` VARCHAR(50) NOT NULL COMMENT '主题名字',
PRIMARY KEY (`categoryid`)
)ENGINE=INNODB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
INSERT INTO `category` (`categoryid`, `pid`, `categoryname`)
VALUES ('2', '1', '信息技术'),('3', '1', '软件开发'),('5', '1', '美术设计'),('4', '3', '数据库'),('8', '2', '办公信息'),('6','3', 'web开发'),('7','5', 'ps技术')
SELECT a.`categoryname` AS '父栏目',b.`categoryname`AS '子栏目'
FROM `category`AS a,`category`AS b
WHERE a.`pid`=b.`categoryid`
SELECT `studentno`,`studentname`,`gradename`
FROM `student` s
INNER JOIN `grade` g
ON s.`gradeid`=g.`gradeid`
SELECT `subjectname`,`gradename`
FROM `grade` g
INNER JOIN `subject` s
ON s.`gradeid`=g.`gradeid`
SELECT s.studentno,studentname,subjectname,studentresult
FROM result r
RIGHT JOIN student s
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` sub
ON sub.`subjectno`=r.`subjectno`
WHERE subjectname = 'C语言-1'
no=r. studentnoINNER JOIN subjectsub ON sub. subjectno=r. subjectno` WHERE subjectname = ‘C语言-1’ – 总结:1.交叉条件对于结果的判断十分重要,值判断先后无关
|