簡體   English   中英

SQL 從 3 個表中獲取所需結果的查詢

[英]SQL query for getting desired result from 3 tables

圖式

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匹配的考試,並查找匹配機構 inn 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來做到這一點:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM