我需要加入4个表:位置,动物,人物,组织和地址。
输入将是组ID,即70
要求:
如果该动物有person_id,则在位置表中,从人员表和地址信息中获取该人的名字和姓氏。
如果组织ID在位,请获取组织名称和地址 来自组织表和地址表。
如何在给定组织ID为70的一个查询中加入这5个表:
带有数据的示例表结构:
表位置
id | group_id | person_id | organization_id | fees1 |fees2 |fees3| received_date |animal_id |
23| 70 | 12 | 0 | 10 |10 |0 | 2017-11-11 | 1 |
24| 70 | 1 | 0 | 10 |10 |0 | 2017-10-11 | 1 |
表动物
id| animal_name |group_id|
1 | demo | 22 | 70
表人
id | first_name | last_name |
1 | Sam | Dam |
表组织
id | org_name |
77 | test_org |
表格地址
id | organization_id | person_id | address1 | country|
45 | 0 | 1 | test address| USA |
group_id 70的预期输出
输出:
location.id | location.group_id | location.person_id | location.organization_id | fees1 |fees2 |fees3| received_date | animal_id | animal_name | first_name |address1 |
23 | 70 | 1 | 70 | 20 |20 |20 | 2017-11-11 | 1 | demo | Sam | test address |
答案 0 :(得分:1)
您可以尝试以下查询
select l.id,l.group_id,l.person_id,l.organization_id,l.fees1,l.fees2,l.fees3,max(l.received_date) as received_date,l.animal_id,p.first_name,aa.address1 from Organization as o inner join location as l on o.id=l.organization_id left join Person as p on l.person_id=p.id inner join Animal as a on l.animal_id=a.id inner join Address as aa on o.id=aa.organization_id where o.id=70 limit 1
或
select l.id,l.group_id,l.person_id,l.organization_id,l.fees1,l.fees2,l.fees3,l.received_date,l.animal_id,p.first_name,aa.address1 from Organization as o inner join location as l on o.id=l.organization_id left join Person as p on l.person_id=p.id inner join Animal as a on l.animal_id=a.id inner join Address as aa on o.id=aa.organization_id where o.id=70 order by l.received_date desc limit 1