SQL选择具有名称的ID

时间:2014-10-18 08:18:50

标签: sql oracle

如何使用名称找到表的ID?

我的数据库架构 BOLD 表示PRIMARY KEY, ITALIC 表示FOREIGN KEY

阶段( stage_id ,take_place,start_loc,end_loc,距离)
骑手( rider_id ,姓名,年份)
结果(stage_id,rider_id, time_seconds)

问题:如果弗雷德布拉德利赢得巡回赛。找到至少在4个阶段击败他的车手,即在21个阶段中至少4个阶段比布拉德利有更好时间的车手。 我按照以下方式完成了。但我不知道如何使用名称检索骑手ID。

select rider.name
from Results res, Results res2, Riders rider
where rider.name like '%Bradley%' and res.stage_id = res2.stage_id and res.time_seconds > res2.time_seconds
    and res2.rider_id = rider.rider_id 
group by rider.name
having count(*) >= 4
order by name;

2 个答案:

答案 0 :(得分:1)

您只需将id添加到selectgroup by列表中即可:

SELECT   rider.id, rider.name
FROM     Results res, Results res2, Riders rider
WHERE    rider.name LIKE '%Bradley%' AND 
         res.stage_id = res2.stage_id AND 
         res.time_seconds > res2.time_seconds AND
         res2.rider_id = rider.rider_id 
GROUP BY rider.id, rider.name
HAVING   COUNT(*) >= 4
ORDER BY name;

答案 1 :(得分:1)

rider.name like '%Bradley%放在where子句中将返回Fred Bradley的结果,这不是问题所要求的

  

至少在4个阶段击败他的车手

尝试

select rider.name
from Results res
join Results res2
on res.stage_id = res2.stage_id and res.time_seconds > res2.time_seconds and res.rider_id = (select r.rider_id from rider r where r.name = 'Fred Bradley')
join  Riders rider
on res2.rider_id = rider.rider_id
group by rider.name
having count(*) >= 4
order by name;