在MySQL中,如何对单个选择使用两次表引用?

时间:2012-02-09 14:27:59

标签: mysql sql database relational-database

示例:

Table: Unit
ID NAME  VALUE
1  Kilo  1000
2  Mega  1000000
3  Giga  1000000000

Table: Storage
ID Title    Drive_value Drive_unit_ID Cache_value Cache_unit_ID 
1  Seagate  100         3             400         1 
2  Scansoft 250         3             80          2 

关系:

Storage.Cache_unit_ID references Unit.ID
Storage.Drive_unit_ID references Unit.ID 

所需目标: 要从存储中选择*,请显示新列'AS'驱动器和'AS'缓存,并通过乘以适当的Unit.VALUE

来显示
 Title     Drive          Cache  
 Seagate   100000000000   400000          
 Scansoft  250000000000   80000000000          

1 个答案:

答案 0 :(得分:1)

只要您对连接的表进行别名,就可以多次加入同一个表:

SELECT s.Title, u1.VALUE * s.Drive_value AS Drive, u2.VALUE * s.Cache_value AS Cache
FROM Storage s
INNER JOIN Unit u1 ON u1.ID = s.Drive_unit_ID
INNER JOIN Unit u2 ON u2.ID = s.Cache_unit_ID