SQL查询两个表

时间:2016-11-21 17:19:55

标签: sql oracle

我遇到查询问题:
我的表格如下:

驱动程序

|DRIVER_ID|FIRST_NAME|LAST_NAME|AGE|
|        1|John      |Smith    |19 |
|        2|Steve     |Oak      |33 |
|        3|Mary      |Sanchez  |22 |

Drivers_in_Teams

|DRIVERS_IN_TEAMS_ID|DRIVER_ID|TEAM_ID|BEG_DATE |END_DATE |
|                  1|        1|      1|18-NOV-05|    -    |
|                  2|        3|      2|10-APR-12|    -    |
|                  3|        2|      3|19-JUL-01|02-AUG-04|

BEG_DATE使用" sysdate-number"

完成

我想制作一个查询,其中显示最旧的名字,名字仍然在团队中。

我尝试了一些我从谷歌找到的例子,但是我无法让它们发挥作用。我是SQL的初学者,我不知道如何进行此查询。

我找到的一个例子

SELECT FIRST_NAME, LAST_NAME 
FROM DRIVER, DRIVERS_IN_TEAMS 
WHERE DRIVER.DRIVER_ID = DRIVERS_IN_TEAMS.DRIVER_ID 
AND DRIVERS_IN_TEAMS.BEG_DATE =  
     SELECT (SELECT MIN(BEG_DATE) 
             FROM DRIVERS_IN_TEAMS) (SELECT MAX(AGE) 
     FROM DRIVERS);

4 个答案:

答案 0 :(得分:0)

试试这个:

select top 1 first_name, last_name from Drivers as d
    inner join Drivers_in_Teams as dit on d.driver_id = dit.driver_id
where isnull(end_date,'')=''
order by age desc

评论您是否有任何问题或代码无效。

答案 1 :(得分:0)

我认为它应该有效。没有资源可以测试和调试。如果有任何问题,请告诉我。

SELECT first_name FROM driver WHERE
driver_id in (select unique(driver_id) from driver_in_teams where end_date is NULL) 
and age =(select MAX(age) from drivers)

替代:

SELECT first_name FROM driver d
INNER JOIN
driver_in_teams dt ON (d.driver_id=dt.driver_id)
WHERE dt.END_DATE IS NULL
AND d.age=(select MAX(age) from drivers)

答案 2 :(得分:0)

SELECT FIRST_NAME, LAST_NAME, AGE 
FROM Drivers
JOIN Drivers_in_Teams ON Drivers.DRIVER_ID = Drivers_in_Teams.DRIVER_ID
WHERE Drivers_in_Teams.END_DATE IS NULL
ORDER BY AGE DESC

这应该加入两个表,每个表都有DRIVER_ID,然后只显示NULL的记录,我认为这些记录是' - '在END_DATE字段中。

答案 3 :(得分:0)

这应该可以解决问题:

-- get the data you want
SELECT first_name, last_name, age FROM drivers d
 WHERE d.age = (
    -- get the max age from drivers still actives
    SELECT MAX(age) FROM driver WHERE driver_id IN (
    -- get drivers still active
        SELECT drive_id FROM drivers_in_teams WHERE end_date IS NULL
    ) x