简体   繁体   中英

Mysql join with 5 table or stored procedure/function

I need to join 4 tables : Location, Animal, Person, Organization and Address.

Input will be group id ie 70

Requirement :

  • Get the latest location of the animal , based on received date.
  • Get the animal name from animal table.
  • if there is a person_id for that animal ,in the location table, get the person first name and last name from Person table and address information.

  • If organization id is there in location , get the organization name and address from Organization table and address table.

How can I join these 5 tables in one query for a given organization id of 70:

Sample Table structure with Data :

Table location

 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        |

Table Animal

  id| animal_name |group_id|
  1 | demo | 22   | 70

Table Person

 id | first_name | last_name |
 1 | Sam        | Dam       |

Table Organization

 id | org_name |
 77 | test_org |

Table Address

 id | organization_id | person_id | address1    | country|
 45 |  0              | 1         | test address| USA    |

Expected output for group_id 70

Output :

 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 |

You can try the below queries

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

or

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM