2014-10-08 115 views
0

我有2個表。我要爲輸出MySQL查詢中的截圖:SQL查詢以獲得期望的結果

enter image description here

有什麼解決方案嗎?

+3

考慮向我們提供您迄今爲止所嘗試的內容,以及您使用的是什麼樣的SQL Enginge也會有所幫助。 – Jeredepp 2014-10-08 07:35:11

+0

您需要使用'UNION'運算符來處理此類查詢。 – mochalygin 2014-10-08 07:36:10

+0

@Jeredepp他可以通過'UNION'操作員輕鬆獲得這樣的輸入。 – mochalygin 2014-10-08 07:45:10

回答

0

試試這個:

SELECT Table_1.Firstname, Table_2.Lastname, Table_2.RF1 AS 'RaterFirst', Table_2.RL1 AS 'RaterLast' FROM Table_1, Table_2 WHERE (Table_1.ID = Table_2.ID) 
UNION 
SELECT Table_1.Firstname, Table_2.Lastname, Table_2.RF2 AS 'RaterFirst', Table_2.RL2 AS 'RaterLast' FROM Table_1, Table_2 WHERE (Table_1.ID = Table_2.ID) 
UNION 
SELECT Table_1.Firstname, Table_2.Lastname, Table_2.RF3 AS 'RaterFirst', Table_2.RL3 AS 'RaterLast' FROM Table_1, Table_2 WHERE (Table_1.ID = Table_2.ID) 

但我想告訴你,這是不是在設計數據庫表TABLE_2 你必須保持多行記錄每個ID的正確方法。 檢查First Normal Form

+0

可能是'ORDER BY Table_1.Firstname,Table_2.Lastname'也需要使用。 – mochalygin 2014-10-08 07:47:25

0

您可以使用此:

Select Firstname, Lastname, Table_2.RF1 AS Raterfirst, Table_2.RL1 AS Raterlast 
From Table_1 
Inner Join Table_2 
ON Table_1.ID = Table_2.ID 
WHERE Raterfirst <> '' OR Raterlast <> '' 

UNION 

Select Firstname, Lastname, Table_2.RF2 AS Raterfirst, Table_2.RL2 AS Raterlast 
From Table_1 
Inner Join Table_2 
ON Table_1.ID = Table_2.ID 
WHERE Raterfirst <> '' OR Raterlast <> '' 

UNION 

Select Firstname, Lastname, Table_2.RF3 AS Raterfirst, Table_2.RL3 AS Raterlast 
From Table_1 
Inner Join Table_2 
ON Table_1.ID = Table_2.ID 
WHERE Raterfirst <> '' OR Raterlast <> '' 

您可以優化SQL命令,例如只使用一個Where表達。

相關問題