2016-03-03 97 views
-2

對不起,我的英語)我有3張桌子。接下來類型:將多行組合成一行並放入表中MySQL

表1 - 用戶

-------------------------------- 
| id  | email | password | 
-------------------------------- 
| 1  | 1  | 3  | 
| 2  | 1  | 4  | 
| 3  | 1  | 3  | 
| 4  | 1  | 4  | 
| 5  | 2  | 3  | 
| 6  | 2  | 4  | 
| 7  | 2  | 3  | 
| 8  | 2  | 4  | 
-------------------------------- 

表2:分數

--------------------------- 
id  | idUser | nameScore| 
-------------------------------- 
| 1  | 1  | df  | 
| 2  | 1  | sa  | 
| 3  | 1  | as  | 
| 4  | 1  | 4  | 
| 5  | 2  | 3  | 
| 6  | 2  | 4  | 
| 7  | 2  | 3  | 
| 8  | 2  | 4  | 
-------------------------------| 

表3:支付

-------------------------------------------------- 
| id  | idScorePayer |idScorePayee| money 
-------------------------------------------------- 
| 1  | 1    | 2  | 1000 
| 2  | 2    | 4  | 700 
| 3  | 3    | 1  | 1500 
| 4  | 4    | 3  | 9000 
--------------------------------------------------- 

我試着去輸出什麼:

----------------------------------------------- 
| id  | emailPayer | emailPayee  | money 
----------------------------------------------- 
| 1  | [email protected]  | [email protected]  | 
| 2  | [email protected]  | [email protected]   | 
| 3  | [email protected]  | [email protected]  | 
| 4  | [email protected]  | [email protected]   | 
| 5  | [email protected]  | [email protected]  | 
| 6  | [email protected]  | [email protected]   | 
| 7  | [email protected]  | [email protected]  | 
| 8  | [email protected]  | [email protected]   | 
----------------------------------------------- 
+0

你可以構建你的表好一點嗎?以及更多地解釋價值? – JanR

+0

你的問題不是很清楚,你會得到黃色,藍色,餅乾,牛奶? \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **]( http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)瞭解如何提高您的問題質量並獲得更好的答案。 –

+0

電子郵件表格未顯示 –

回答

0

下面的查詢應該工作:

select u1.email as emailPayer, u2.email as emailPayee, amount 
from users u1 join scores s1 on u1.id = s1.idUser 
join payment on s1.id = payment.idScorePayer 
join scores s2 on payment.idScorePayee = s2.idUser 
join users u2 on u2.id = s2.idUser 
0

我沒有MySQL實例再次進行測試,我上的電子郵件表的猜測,但我認爲這會是這樣的:

SELECT 
    users.id, 
    email1.email_name "emailPayer", 
    email2.email_addr "emailPayee", 
    payment.money 
FROM 
    users 
    JOIN scores ON (users.id = scores.idUser) 
    JOIN payment ON (scores.id = payment.idScorePayer) 
    JOIN email email1 ON (scores.idScorePayer = email.id) 
    JOIN email email2 ON (scores.idSCorePayee = email.id) 
+0

http://sqlfiddle.com/#!9/dfaa19/1 –