简体   繁体   中英

sql query help multi joins?

here are my tables, im using sql developer oracle

Carowner(Carowner id, carowner-name,)

Car (Carid, car-name, carowner-id*)

Driver(driver_licenceno, driver-name)

Race(Race no, race-name, prize-money, race-date)

RaceEntry(Race no*, Car id*, Driver_licenceno*, finishing_position)

im trying to list to do the query below

which drivers have come second in races from the start of this year. lncluding race name, driver name, and the name of the car in the output

i have attempted

select r.racename, d.driver-name, c.carowner-name

from race r, driver d, car c, raceentry re

where re.finishing_position = 2 and r.race-date is ...

First off, multiple joins in the where clause are hard to get used to when you define more than 3 or 4 tables IMHO.

Do this instead:

Select 
  a.columnfroma
, b.columnfromb
, c.columnfromc
from tablea a
  join tableb b on a.columnAandBShare = b.columnAandBShare
  join tablec c on b.columnBandCShare = c.columnBandCShare

This while no one would say is a method you have to use, it is a much more readable method of performing joins.

Otherwise you are doing the joins in the where clause and if you have other predicates with your joins you are going to have to comment out which is which if you ever need to go back and look at it.

Something like:

select r.racename, d.driver-name, c.carowner-name
from race r
join raceentry re on r.race_no = re.race_no
join car c on re.car_Id = c.car_id
join driver d on re.driverliscenceNo = d.driverliscenceNo
where re.finishing_position = 2 and r.race-date >='20130101'

This assumes only one car and one driver with a finsih place of 2nd in a particular race. You may need more conditions otherwise. If this is your own table design, you need to start right now learning to be consistent in your nameing between tables. It is important. Fields that are in multiple tables should have the same name and data type. Also you need to stop using implicit syntax. This ia aSQL antipattern and a very poor programming technique. It leads to mistakes such as accidental cross joins and is harder to read and maintain when things get more complex. As you are clearly learning, you need to stop this bad habit right now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM