mysql - 从 3 个表中获取所需结果的 SQL 查询
问题描述
架构
CREATE TABLE IF NOT EXISTS `exams` (
`id` int(6) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `institutions` (
`id` int(6) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `exam_scores` (
`id` int(6) unsigned NOT NULL,
`exam_id` int(6) NOT NULL,
`institution_id` int(6) NOT NULL,
`score` int(5)
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `exams` (`id`, `name`) VALUES
('1', 'exam1'),
('2', 'exam2'),
('3', 'exam3'),
('4', 'exam4');
('5', 'exam5');
INSERT INTO `institutions` (`id`, `name`) VALUES
('1', 'institution1'),
('2', 'institution2'),
('3', 'institution3'),
('4', 'institution4');
('5', 'institution5');
INSERT INTO `exam_scores` (`id`, `exam_id`, `institution_id`, `score`) VALUES
('1', '1', 1, 40),
('2', '2', 1, 45),
('3', '3', 2, 35),
('4', '1', 2, 30);
('5', '4', 3, 40);
现在用户将输入exm1
我正在尝试创建一个查询来查找所有相关的考试,如下所示。查找匹配输入的考试exm1
,还可以找到匹配机构客栈exam_scores
表中存在的其他考试。
示例 1:输入exm4
desired output
| exm4 |
示例 2:输入exm3
desired ouput
| exm3 |
| exm1 |
示例 3:输入exm1
desired output
| exm1 |
| exm2 |
| exm3 |
到目前为止,我只提出了一个只提供匹配考试的查询:)
select exams.name from exams
inner join exam_scores on exam_scores.exam_id = exams.id
// ??
where exams.id = 1
解决方案
您可以使用join
s 执行此操作:
select distinct e1.name
from exams e1
inner join exam_scores es1 on es1.exam_id = e1.id
inner join exam_scores es2 on es2.institution_id = es1.institution_id
inner join exams e2 on e2.id = es2.exam_id
where e2.name = ?
推荐阅读
- javascript - 怎么管理第二行商品,价格列不能显示价格?
- python-3.x - Python:重命名外部硬盘驱动器磁盘
- c# - ScriptManager 的并发问题
- java - 我查询以获取列默认值,但出现 ORA-17003
- linux - 这个脚本如何将十六进制转换为ASCII?
- azure - 允许访问 Azure Web 应用的等效 Azure 服务
- continuous-integration - Gitlab CI/CD 部署到本地 Tomcat
- c# - 从另一个窗口更新主窗口列表
- redux - GraphQL 查询在突变后仅获取一次数据
- f# - c# 到 f# 当 3rd 方库想要一个 byref 作为输出参数时