Java学习-MySQL-DQL数据查询-自连接
初始化
CREATE DATABASE IF NOT EXISTS `school`;
USE `school`;
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.categoryid=b.pid
初始化
CREATE DATABASE IF NOT EXISTS `school`;
USE `school`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`(
`studentno` INT(4) NOT NULL COMMENT '学号',
`studentname` VARCHAR(20) DEFAULT NULL COMMENT '学生姓名',
`sex` TINYINT(1) DEFAULT NULL COMMENT '性别,0或1',
`gradeid` INT(11) DEFAULT NULL COMMENT '年级编号',
`address` VARCHAR(255) NOT NULL COMMENT '地址,允许为空',
PRIMARY KEY (`studentno`)
)ENGINE=MYISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade`(
`gradeid` INT(11) NOT NULL AUTO_INCREMENT COMMENT '年级编号',
`gradename` VARCHAR(50) NOT NULL COMMENT '年级名称',
PRIMARY KEY (`gradeid`)
) ENGINE=INNODB AUTO_INCREMENT = 6 DEFAULT CHARSET = utf8;
查询学生的年级
SELECT `studentno`,`studentname`,`gradename`
FROM student s
INNER JOIN grade g
ON s.`gradeid`=g.`gradeid`
查询科目的年级
SELECT `subjectno`,`subjectname`,`gradename`
FROM `subject` s
INNER JOIN `grade` g
ON s.`gradeid`=g.`gradeid`
查询参加数据库结构-3考试的学生信息
SELECT s.`studentno`,`studentname`,`subjectname`,`studentresult`
FROM `student` s
INNER JOIN `result` r
ON s.`studentno`=r.`studentno`
INNER JOIN `subject` sub
ON r.`subjectno`=sub.`subjectno`
WHERE `subjectname`= '数据库结构-3'