0

我需要创建一个查询来查找在参加更多考试时考试成绩会降低的司机的姓名。所以我有以下表格:

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

编辑!我让它工作了!感谢大家的投入!

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

3 回答 3

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 。

于 2012-11-09T13:59:02.390 回答
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

查询选择驾驶员参加的所有考试对,其中分数较低且日期较大

于 2012-11-09T13:46:28.800 回答
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)
于 2012-11-09T14:04:35.967 回答