Mysql 用于从3个表中获取所需结果的SQL查询
模式Mysql 用于从3个表中获取所需结果的SQL查询,mysql,sql,join,inner-join,where-clause,Mysql,Sql,Join,Inner Join,Where Clause,模式 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)
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
desired output
| exm4 |
desired ouput
| exm3 |
| exm1 |
desired output
| exm1 |
| exm2 |
| exm3 |
我试图创建一个查询来查找所有相关的考试,如下所示。
查找与输入匹配的考试exm1
,并在考试分数表中查找匹配机构中存在的其他考试
示例1:输入exm4
desired output
| exm4 |
desired ouput
| exm3 |
| exm1 |
desired output
| exm1 |
| exm2 |
| exm3 |
示例2:输入exm3
desired output
| exm4 |
desired ouput
| exm3 |
| exm1 |
desired output
| exm1 |
| exm2 |
| exm3 |
示例3:输入exm1
desired output
| exm4 |
desired ouput
| exm3 |
| exm1 |
desired output
| exm1 |
| exm2 |
| exm3 |
到目前为止,我只提出了一个只给出匹配考试的查询:)
您可以使用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 = ?
我建议使用变量,因为它允许您使用SET操作轻松地更新变量的值(例如,如果您的用户要使用GUI)
在下面的代码中,您只需将exm1
值更改为所需的值
declare @input nvarchar(10);
set @input = 'exm1';
select distinct a.name
from exams a
inner join exam_scores b on b.exam_id = a.id
inner join exam_scores b2 on b2.institution_id = b.institution_id
inner join exams a2 on a2.id = b2.exam_id
where a2.name = @input
exm1
的输出不应该是exm1
和exm2
?@Tajni,因为exm1
与机构(id:2)
匹配,并且机构id 2
具有exm3:),所以输出是正确的。