2012-02-09 57 views
0

例子:在MySQL中,如何使用我的表引用兩次進行單個選擇?

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 

預期目標: 做一個SELECT * FROM存儲,顯示 'AS' 驅動新列和 'AS' 緩存並通過乘以適當的單位來顯示.VALUE

Title  Drive   Cache 
Seagate 100000000000 400000   
Scansoft 250000000000 80000000000   

回答

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 
相關問題