简体   繁体   English

SQL查询帮助多联接?

[英]sql query help multi joins?

here are my tables, im using sql developer oracle 这是我的表格,即时通讯使用sql developer oracle

Carowner(Carowner id, carowner-name,) Carowner(Carowner ID,Carowner-name,)

Car (Carid, car-name, carowner-id*) 汽车(Carid,汽车名称,carowner-id *)

Driver(driver_licenceno, driver-name) 驱动程序(driver_licenceno,驱动程序名称)

Race(Race no, race-name, prize-money, race-date) 比赛(种族,比赛名称,奖金,比赛日期)

RaceEntry(Race no*, Car id*, Driver_licenceno*, finishing_position) RaceEntry(种族编号*,汽车编号*,驾驶员执照编号*,终点排名)

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. 首先,当您定义3个或4个以上的表IMHO时,很难习惯where子句中的多个联接。

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. 否则,您将在where子句中进行连接,并且如果您的连接还有其他谓词,则必须注释掉哪个,如果您需要返回并查看它的话。

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. 这是一个SQL反模式,并且是一种非常糟糕的编程技术。 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. 当您清楚地学习时,您需要立即停止这种不良习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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