简体   繁体   中英

SQL query for getting desired result from 3 tables

Schema

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);

Now the user will input exm1

I am trying to create a query to find all related exams like below. Find exams matching input exm1 and also find other exams existing in matched institutions inn exam_scores table.

Example 1: input exm4

desired output
| exm4 |

Example 2: input exm3

desired ouput 
| exm3 |
| exm1 |

Example 3: input exm1

desired output 
| exm1 |
| exm2 |
| exm3 | 

So far I have only come up with a query which gives only matched exam:)

select exams.name from exams
inner join exam_scores on exam_scores.exam_id = exams.id
// ??
where exams.id = 1

You can do this with 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 = ?

I recommend using a variable, because it will allow you to easily update the value of the variable using SET operations (if, for example, you're user is going to use a GUI).

In the below code, you just need to change the exm1 value to the desired value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM