简体   繁体   English

MySQL多表联接与四个表(Race和Results表)

[英]MySQL Multiple table joins with four tables (Race and Results tables)

I need to make a MySQl query to get data from multiple tables in a database, and i have been trying but can't seem to get it right. 我需要进行MySQl查询才能从数据库的多个表中获取数据,我一直在尝试但似乎无法正确处理。 Below is a example of my tables and what i would like. 以下是我的表格和我想要的示例。

The Database Tables Are: 数据库表是:

+-------------------+  
|        Car        |  
+-------------------+  
| Car_ID (Int)      |   
| Car_Name (String) |  
+-------------------+  

Example of Car: 汽车示例:

Car_ID: 1  
Car_Name: BMW M3  

+-------------------+  
|       Race        |  
+-------------------+  
| Race_ID (Int)     |  
| Race_Car1 (Int)   |  
| Race_Car2 (Int)   |  
| Race_Number (Int) |  
+-------------------+  

Example of Race: 比赛示例:

Race_ID: 11  
Race_Car1: 3  
Race_Car2: 2  
Race_Number: 6  

+-------------------+  
|      Result       |  
+-------------------+  
| Result_ID (Int)   |   
| Result_Number (Int)|  
| Result_Result (Int)|  
+-------------------+  

Example of Result: 结果示例:

Result_ID: 1  
Result_Number: 6  
Result_Result: 2

+-------------------+  
|    ResultType     |  
+-------------------+  
| ResultType_ID (Int)|   
| ResultType_Name (String)|  
+-------------------+  

Example of ResultType: ResultType的示例:

ResultType_ID: 1  
ResultType_Name: Car1 Win   

I would like the query that will join the Car table to the Race tables Race_Car1 and Race_Car2 fields and then the result from the Result table Result_Number must be joined with the Race_Number field and also the Result_Type must be joined into the Result_Result field. 我希望将Car表加入Race表Race_Car1和Race_Car2字段的查询,然后将Result表Result_Number的结果与Race_Number字段结合,并且Result_Type也必须加入Result_Result字段。

Basically i want a result like this: 基本上我想要这样的结果:

Race_Car1 Race_Car2 Result_Result Race_Number  
BMW M3 | Ford Focus RS | Car1 Win | 6

you could use a self join for join the car moltiple time 您可以使用自我加入来参加汽车多时

in my answer i show the winner car name instead of car1 or car2 在我的回答中,我显示获胜者的汽车名称,而不是car1或car2

  select a.car_name  car_1, b.car_name car_2, c.car_name winner, d.race_nymber
  from  race d
  inner join car a on a.car_ID = d.race_car_1
  inner join car b on b.car_ID = d.race_car_2
  inner join result t on t.Result_Number = d.Result_Number
  inner join car c on c.car_ID = t.Result_Result

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

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