또 다른 방법은 임시 테이블을 사용하여 다른 값을 유지하는 것입니다. 먼저 정확한 일치 항목을 삽입 한 다음 초기 선택 항목에없는 일치 항목을 삽입하고 마지막으로 임시 테이블의 모든 결과를 가져옵니다. 이 솔루션은 다른 것보다 더 많은 코드이므로 다른 대안으로 추가하십시오.
예 (SqlFiddle) :
스키마 처음
create table students
(code integer,
name varchar(50),
topic varchar(50),
value integer);
create table subjects
(subject varchar(50),
value varchar(50),
result integer);
insert students
(code, name, topic, value)
values
(1, 'Doe, John', 'History', 25),
(2, 'Doe, John', 'Geography', 30),
(3, 'Doe, Jane', 'Mathematics', 45),
(4, 'Doe, Jane', 'Brad Pitt Studies', 100);
insert subjects
(subject, value, result)
values
('History', 25, 95),
('History', 30, 84),
('History', 35, 75),
('Geography', 35, 51),
('Geography', 40, 84),
('Geography', 45, 65),
('Mathematics', 45, 32),
('Mathematics', 50, 38),
('Mathematics', 55, 15),
('Brad Pitt Studies', 100, 92),
('Brad Pitt Studies', 90, 90);
실제 SQL 쿼리 :
-- Temp table to hold our results
create temporary table tempresult
(code integer,
name varchar(50),
topic varchar(50),
studentvalue integer,
subjectvalue integer,
result integer);
-- Get the exact results
insert tempresult
(code,
name,
topic,
studentvalue,
subjectvalue,
result)
select stu.code,
stu.name,
stu.topic,
stu.value as 'student_value',
sub.value as 'subject_value',
sub.result
from students stu
join
subjects sub on sub.subject = stu.topic
and sub.value = stu.value;
-- Get the non-exact results, excluding the 'students' that we already
-- got in the first insert
insert tempresult
(code,
name,
topic,
studentvalue,
subjectvalue,
result)
select stu.code,
stu.name,
stu.topic,
stu.value as 'student_value',
sub.value as 'subject_value',
sub.result
from students stu
join
subjects sub on sub.subject = stu.topic
-- Business logic here: Take lowest subject value that is just above the student's value
and sub.value = (select min(sub2.value)
from subjects sub2
where sub2.subject = stu.topic
and sub2.value > stu.value)
where not exists (select 1
from tempresult tmp
where tmp.code = stu.code
and tmp.name = stu.name
and tmp.topic = stu.topic)
-- Get our resultset
select code,
name,
topic,
studentvalue,
subjectvalue,
result
from tempresult
order by code,
name,
topic,
studentvalue,
subjectvalue,
result
을하지만,이 경우 table1''의 값이 모두보다 낮은 'table2'의 값 ... 당신은 무엇을하고 싶습니까? –
@DavidFaber 나는 첫 번째 테이블을 엉망으로 만들었다. 나는 그 포스트를 편집 할 것이고, 혼란에 대해 유감스럽게 생각한다. –
주제가 주제와 비슷합니까? – Strawberry