douchang8758 2016-01-29 10:51
浏览 19
已采纳

使用连接从三个表中获取结果,其中一个表包含多个结果

I have three tables with the following columns and data:

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

Now my query will be

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

How can I join these three queries and get a single query. Please note that table_two will get multiple rows so I want take the first matched row and omit the rest where table_two.id matches.

Expected Result:

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

SOLVED ANSWER:

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
  • 写回答

1条回答 默认 最新

  • douxiong4892 2016-01-29 11:02
    关注

    Would you try:

          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
    

    You can have more elegant queries using advanced RDBMS, but not with MySQL unfortunately.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了