2014-06-12 57 views
0

我有兩個表,一個是串行和主。我在下面顯示兩種表格格式。我想獲得下面的確切輸出。我是這個領域的新手。請幫助我做到這一點。我怎樣才能得到從子表的序列

串行

FLD_ID FLD_SERIAL FLD_TYPE 
1 1234-34563-2323-2345 MONITOR 
2 1234-34563-2323-2346 KEYBOARD 
3 1234-34563-2323-2347 MONITOR 
4 1234-34563-2323-2348 MONITOR 
5 1234-34563-2323-2349 MONITOR 
6 1234-34563-2323-2350 MONITOR 
7 1234-34563-2323-2351 KEYBOARD 
8 1234-34563-2323-2352 CPU 
9 1234-34563-2323-2353 CPU 
10 1234-34563-2323-2354 CPU 

主要

FLD_ID FLD_CPU FLD_MONITOR FLD_KEYBOARD 
1   8 1   7 
2   9 4 
3   10    2 

期望輸出

FLD_ID FLD_CPU     FLD_MONITOR   FLD_KEYBOARD 
1 1234-34563-2323-2352 1234-34563-2323-2345 1234-34563-2323-2351 
2 1234-34563-2323-2353 1234-34563-2323-2348  
3 1234-34563-2323-2354      1234-34563-2323-2346 

回答

0

像這樣的事情會爲你工作:

SELECT 
    `FLD_ID`, 
    IFNULL((SELECT `FLD_SERIAL` FROM `Serial` WHERE `FLD_ID` = `FLD_CPU`),'') AS `FLD_CPU`, 
    IFNULL((SELECT `FLD_SERIAL` FROM `Serial` WHERE `FLD_ID` = `FLD_MONITOR`),'') AS `FLD_MONITOR`, 
    IFNULL((SELECT `FLD_SERIAL` FROM `Serial` WHERE `FLD_ID` = `FLD_KEYBOARD`),'') AS `FLD_KEYBOARD` 
FROM 
    `Main` 
0
select FLD_ID, cpu.FLD_SERIAL as FLD_CPU, mon.FLD_SERIAL as FLD_MONITOR, kbd.FLD_SERIAL as FLD_KEYBOARD 
from main 
left join Serial as cpu on FLD_CPU = cpu.FLD_ID 
left join Serial as mon on FLD_MONITOR = mon.FLD_ID 
left join Serial as kbd on FLD_KEYBOARD = kbd.FLD_ID 

(未經測試)

編輯: 爲了確保數據庫的一致性,你也應該檢查是否所有條目標有「CPU」相當於CPU領域中的主表,同樣的顯示器和鍵盤。