2016-01-29 58 views
0

我有以下的列和數據三個表的結果是:得到三個表使用連接從一個表中包含多個結果

table_one

id | balance 
100 | 10.00 
101 | 5.00 
102 | 8.00 

table_two

id | number 
100 | 0890980980 
100 | 7657657655 
101 | 7657657656 
102 | 1231231233 

Table_Three中

id | name  | active 
100 | nameOne | 1 
101 | nameTwo | 0 
102 | namrThree | 1 

現在我的查詢將是

Query 1. SELECT * FROM table_one WHERE balance <= 8 
Query 2. SELECT number(only first_matched_row) FROM table_two WHERE table_one.id = table_two.id 
Query 3. SELECT name FROM table_three WHERE table_three.id = table_one.id AND table_three.active = 1 

如何加入這三個查詢並獲得單個查詢。 請注意,table_two將獲得多行,所以我想採取匹配的第一行,並省略table_two.id匹配的其餘部分。

預期結果:

id | name  | number 
100 | nameOne | 0890890890 
102 | nameThree | 1231231233 

解決的答案:

Select onetwo.id, three.name, two.number from 
(Select two.id from 
(SELECT id as id1 FROM table_one WHERE balance <= 8)one 
inner join 
table_two two on one.id1 = two.id 
)onetwo 
inner join 
table_two two on two.id=onetwo.id 
inner join 
table_three three on three.id = onetwo.id AND three.active = 1 group by two.id 
+0

預期結果是什麼? – Naruto

回答

1

你試試:

 Select onetwo.id, three.name, onetwo.number from 
(Select two.id from 
(SELECT id as id1 FROM table_one WHERE balance <= 8)one 
inner join 
table_two two on one.id1 = two.id 
)onetwo 
inner join 
table_three three on three.id = onetwo.id AND three.active = 1 group by onetwo.id 

可以使用先進的RDBMS有更優雅的查詢,但不能與MySQL不幸的。

+0

錯誤代碼:1060重複的列名的 'id' –

+0

SELECT ID FROM table_one WHERE平衡<= 8工作正常,但 從 選擇*(SELECT ID FROM table_one WHERE平衡<= 8)一種 內部聯接 table_two兩個在one.id = two.id 限制1只返回一個。實際結果應該返回ID號碼101和102.另外,如果餘額<= 10,那麼當限制1被省略時,ID號碼100(所有3行)都會返回。 –

+0

查詢已更新,現在可以查看嗎? –

相關問題