我需要创建一个查询,以便在参加更多考试时找到考试成绩较低的驾驶员姓名。所以我有以下表格:
branch(branch_id, branch_name, branch_addr, branch_city, branch_phone);
driver(driver_ssn, driver_name, driver_addr, driver_city, driver_birthdate, driver_phone);
license(license_no, driver_ssn, license_type, license_class, license_expiry, issue_date, branch_id);
exam(driver_ssn, branch_id, exam_date, exam_type, exam_score);
** exam_date是日期
所以我正在使用表格驱动程序和考试。我想以某种方式检查exam_date> anotherDate,同时检查exam_score
*编辑
这是我提出的,但我觉得有些语法是非法的。我一直收到语法错误。
s.executeQuery("SELECT driver_name " +
"FROM driver " +
"WHERE driver.driver_ssn IN " +
"(SELECT e1.driver_ssn" +
"FROM exam e1" +
"WHERE e1.exam_score < " +
"(SELECT e2.exam_score FROM exam e2)" +
"AND e1.exam_date > " +
"(SELECT e2.exam_date FROM exam e2)");
EDIT!我搞定了!感谢大家的投入!
SELECT driver.driver_name
FROM driver
WHERE driver.driver_ssn IN
(SELECT e1.driver_ssn
FROM exam e1, exam e2, driver d
WHERE e1.exam_score < e2.exam_score
AND e1.exam_date > e2.exam_date
AND e1.driver_ssn=e2.driver_ssn)
答案 0 :(得分:1)
您需要进行自我加入。请参阅此示例并将其用于您的架构。
select d.name,
es.date_taken as 'prev date',
es.score as 'prev score',
es.date_taken as 'new date',
es_newer.score as 'new score'
from driver d
inner join exam_score es
on d.id = es.driver_id
left outer join exam_score es_newer
on d.id = es_newer.driver_id
and es_newer.date_taken > es.date_taken
and es_newer.score < es.score
where es_newer.id is not null
以下是我要演示的SQL Fiddle。
答案 1 :(得分:0)
SELECT返回一个集合,您无法将单个值与集合进行比较。你可以尝试这些方面的东西。这与你的相似,并没有处理三个考试案例: -
SELECT driver_name
FROM driver
JOIN exam e1 ON driver_ssn
JOIN exam e2 ON driver_ssn
WHERE e1.exam_score < e2.exam_score
AND e1.exam_date > e2.exam_date
查询选择分数较少且日期较大的驱动程序所采取的所有检查对
答案 2 :(得分:0)
简单地解决这个问题就是让那些参加过几次考试并且第二次得分较低的司机。
要比较同一个表中的列,SQL使用自联接。您的加入条件应包括:
select e1.driver_ssn, e1.exam_type, e1.exam_score as score_before,
e2.exam_score as score_after
exam e1 join exam e2 on (e1.driver_ssn = e2.driver_ssn and
e1.exam_type = e2.exam_type and
e1.exam_date < e2.exam_date and
e1.exam_score > e2.exam_score)