我有三个包含以下列和数据的表:
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 :(得分: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。