2013-05-10 67 views
0

如果我有這兩個表:如何從兩個表中選擇?

table_user 
Id name lname 
1 Mark Brown 
2 Martha Fox 

table_score_start: 
user_Id score 
2  5 

table_score_last: 
user_Id score 
1  3 
2  4 

我如何可以顯示下面的查詢結果呢?

ID名稱LNAME得分得分 1馬克·布朗3 2瑪莎·福克斯5 4

我試圖

SELECT table_user.Id, table_user.name, table_user.lname, table_score_start.score, 
table_score_last.score FROM table_user, table_score_start, table_score_last 

但它不工作

我也試過

SELECT table_user.Id, table_user.name, table_user.lname, table_score_start.score, 
table_score_last.score FROM table_user, table_score_start, table_score_last WHERE table_user.Id = table_score_start.user_Id 

我想要顯示所有的記錄認爲包括那些不是在一個或兩個表的表table_score_start和table_score_last

+0

什麼是錯誤?或者只是空的結果? – powtac 2013-05-10 18:59:47

+0

@ antonioj1015做一個好的支持者。開始接受答案。 – 2013-05-11 09:27:59

+0

你解決了你的問題嗎? – 2013-06-12 22:42:00

回答

2

嘗試以下查詢:

SELECT u.Id, u.name, u.lname, s.score, l.score FROM table_user u, 
table_score_start s, table_score_last l WHERE u.id = s.user_id 
AND u.id = l.user_id 

或者使用聯接:

SELECT u.Id, u.name, u.lname, s.score, l.score FROM table_user u 
INNER JOIN table_score_start s ON (u.id = s.user_id) 
INNER JOIN table_score_last l ON (u.id = l.user_id) 

你可以閱讀更多關於MySQL加入這篇文章:http://dev.mysql.com/doc/refman/5.0/en/join.html

2
select a.Id, a.name, a.lname, b.score as start_score, c.score as last_score from table_user a 
inner join table_score_start b on (a.Id = b.user_Id) 
inner join table_score_last c on (a.Id = c.userId) 

inner joinleft join取決於您的需求。

0
SELECT `user`.*, `start`.score, `last`.score 
FROM table_user `user`, table_score_start `start`, table_score_last `last` 
WHERE `start`.user_Id = `user`.Id 
AND `last`.user_Id = `user`.Id; 
0

像這樣的東西應該做的伎倆:

SELECT u.ID, u.name, u.lname, start.score, last.score 
FROM table_user AS u LEFT JOIN table_Score_Start AS Start on u.ID = Start.ID 
LEFT JOIN table_Score_last AS Last on u.id = Last.ID 

它不在我頭頂,但應該讓你進入球場。你可能不得不做一些MySQL語法的調整,我一直在SQL Server中工作。

0

當您針對多個表運行SELECT時,還應在這些表之間包含JOIN條件。這裏的地方開始閱讀JOINS

請嘗試以下操作。也請不要使用別名,這會使代碼更容易閱讀,但對執行沒有影響。

SELECT u.Id 
     ,u.name 
     ,u.lname 
     ,ss.score 
     ,sl.score 
FROM table_user u 
INNER JOIN 
     table_score_start ss 
ON  ss.user_ID = u.Id 
INNER JOIN 
     table_score_last sl 
ON  sl.user_ID = u.Id 
0

在其他的答案我看到INNER JOIN,但因爲你還希望看到沒有開始或結束的分數(或兩者)的記錄,你應該使用LEFT JOIN這樣的:

SELECT a.Id, a.name, a.lname, b.score as start_score, c.score as last_score 
FROM table_user a 
LEFT join table_score_start b on (a.Id = b.user_Id) 
LEFT join table_score_last c on (a.Id = c.user_Id)