我有三个表,其中包含以下列和数据:
表一
id | balance
100 | 10.00
101 | 5.00
102 | 8.00
表二
id | number
100 | 0890980980
100 | 7657657655
101 | 7657657656
102 | 1231231233
表三
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
最佳答案
你会尝试吗:
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。
关于php - 使用连接从三个表中获取结果,其中一个表包含多个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35082650/