JOIN multiple tables, concatenate name strings, and hierarchically group data

43 Views Asked by At

I have been trying to get details from Contacts table, from Another table with Id's for these contacts, I think it has to do with logic, I am not not a pro yet.

These are my Tables:

g3cc_cntcts_and_employers:

id | employer_id | employee_id | verified | active  
1  |     1       |     2           1          1
2  |     1       |     3           1          0
3  |     1       |     4           0          1
4  |     1       |     5           0          0
5  |     1       |     5           0          0
6  |     6       |     7           1          1
7  |     6       |     4           0          0

g3cc_contactus:

id   |  nombre  |   apellidos
1    |  BOSS    |     CEO
2    |  Perry   |    Smith
3    |  John    |     Doe
4    |  Jane    |    Malme
5    |  Mary    |    Johnson
6    |  Another |    Employer
7    |  Ann     |    Clark

Desired Report:

Employer And Employees
    BOSS CEO
        Perry Smith  | 1  |  1
        John Doe     | 1  |  0
        Jane Malme   | 0  |  1
        Mary Johnson | 0  |  0

Another Employer
    Jane Malme   | 0  |  0
    Ann Clark    | 1  |  1

I already tried from examples from this and other places, I have two queries but I still can't get it to work.

`My Qry 1:

SELECT * FROM (
    SELECT id, nombre, apellidos
    FROM g3cc_contactus
    WHERE id=285
    GROUP BY 1  
) id JOIN (
    SELECT employee_id, active, verified
    FROM g3cc_cntcts_and_employers
    GROUP BY 1  
) employee_id;

My Qry 2:

SELECT * FROM
(SELECT id, username 
    FROM g3cc_contactus) a
JOIN
(SELECT employer_id, employee_id
    FROM g3cc_cntcts_and_employers) b
ON a.id = b.employer_id AND a.id = b.employee_id;
1

There are 1 best solutions below

1
MorganFreeFarm On BEST ANSWER

To get raw data, you could try with:

SELECT
    e.nombre || ' ' || e.apellidos AS Employer,
    c.nombre || ' ' || c.apellidos AS Employee,
    ec.verified,
    ec.active
FROM
    g3cc_cntcts_and_employers ec
JOIN
    g3cc_contactus e ON ec.employer_id = e.id
JOIN
    g3cc_contactus c ON ec.employee_id = c.id
ORDER BY
    e.nombre, e.apellidos, c.nombre, c.apellidos;

If you want to get exact result you have to write some PHP.