2016-01-29 56 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

查询已更新,现在可以查看吗? –

相关问题