I have the following tables in my database.
TABLE_EMPLOYEES
_________________________________________________
| id | name | last name | email |
-------------------------------------------------
| 1 | Henry | Smith | [email protected] |
| 2 | Scarlet | Rogers | [email protected] |
| 3 | John | Adams | [email protected] |
=================================================
TABLE_AVATAR
_________________________________
| id | employee_id | avatar_name |
---------------------------------
| 99 | 1 | henry84 |
|100 | 1 | henry84_ |
|101 | 1 | henry84- |
|442 | 2 | scarlet99 |
|924 | 3 | john-007 |
|926 | 3 | john-008 |
=================================
TABLE_DOCUMENTS
___________________________________
| id | employee_id | document_name |
-----------------------------------
|124 | 2 | cv.doc |
|125 | 2 | resume.pdf |
|126 | 2 | scan-01.jpg |
|127 | 2 | dl.jpg |
|396 | 3 | cv-john.doc |
|397 | 3 | scan-2403.jpg |
===================================
My goal is to retrieve all data from all the tables for each employee. TABLE_EMPLOYEES will contain 1 row per record (I need all data), TABLE_AVATAR can hold many rows per record (I only need the newest one (id desc)), and TABLE_DOCUMENTS can hold many rows per record as well as none at all (I need to get all rows per record if any). I know I can join tables by employee_id, but I'm stock getting only one record from TABLE_AVATAR and all records from TABLE_DOCUMENTS.
Any suggestions?
Thanks, Carlos
Here I have used GROUP_CONCAT group function to get the document_ids to one column.
select employee.*,GROUP_CONCAT(documents.document_name) document_name,(SELECT MAX(id) as avatar_id from zz2 where zz2.employee_id = employee.id ) from zz1 employee LEFT JOIN zz3 documents on documents.employee_id = employee.id group by
employee.id
This will give you the result that is mentioned below.
id name last name mail documents avatar_id
1 henry smith [email protected] NULL 101
2 scarlet rogers [email protected] 3.jpg,4.jpg,1.jpg,2.jpg 442
3 jon adam [email protected] 5.jpg,6.jpg 926
Just replace your table names with zz1,zz2,zz3. I guess this will help you to solve your problem.