Question

How should I change the following MySql query...

select o.name, e.name, c.phone from organization o, employee e, contact c

which produces this...

Organization  | Employee   | Contact Number
--------------+-------------+-----------------
Acme Cement   | John Doe   | 555-1234
Acme Cement   | Jane Plain | 555-1212
Acme Cement   | Bob knob   | 555-1111
Hack IT       | Mike Smith | 444-2343
Hack IT       | Ed Snowdon | 444-4444

so that it returns this...

Organization  | Employee   | Contact Number
--------------+-------------+-----------------
Acme Cement   | John Doe   | 555-1234
              | Jane Plain | 555-1212
              | Bob knob   | 555-1111
Hack IT       | Mike Smith | 444-2343
              | Ed Snowdon | 444-4444
Was it helpful?

Solution

You can't achieve the result set you want using MySQL. The result of your query will always have o.name in the rows.

However, if you use a GROUP BY and GROUP_CONCAT function then maybe you can find it easier to deal with the results:

SELECT o.name, GROUP_CONCAT(e.name), GROUP_CONCAT(c.phone)
FROM organization o
LEFT JOIN employee e ON e.orgid = o.id
LEFT JOIN contact c ON c.empid = e.id
GROUP BY o.name

Your results would be:

| Organization | Employee                       | Contact Number             |
|--------------+--------------------------------+----------------------------|
| Acme Cement  | John Doe,Jane Plain,Bob knob   | 555-1234,555-1212,555-1111 |
| Hack IT      | Mike Smith,Ed Snowdon          | 444-2343,444-4444          |

Now, instead of results that hide o.name for successive rows, you have one row per Organization, and the other columns are comma lists of the related data. The function lets you use a delimiter other than comma if you like.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top