I have two tables with shared keys and I'm trying to join them and output the results to one table. The problem I'm having is the second table has multiple values for the shared key.
hosts
host_object_id | hostname |
1 | America1 |
2 | Another1 |
vars
object_id | varname | varvalue |
1 | type | Country |
1 | location | N.A. |
1 | capital | D.C. |
2 | type | Another |
2 | location | Location |
2 | capital | Example |
What I'm trying to get is
Hostname | Type | Location |
America | Country | N.A. |
Another1 | Another | Location |
Best Answer
You have two possibilities:
Two joins. Probably a good alternative if you do a limited search, and don't want all available attributes (i.e.: you ignore capital)
max(case) and GROUP BY. This is a typical approach to
unpivot
in standard SQL. This is normally faster went you either want all attributes (type
,location
,capital
), or you don't limit your queries with aWHERE
that restricts the result significantly. (In your case, withoutWHERE
, I'd choose this approach:In both cases, you'll get:
NOTE 1: This assumes that
vars
hasPRIMARY KEY (object_id, varname)
. Otherwise, you could have more than onetype
orlocation
perobject_id
, and that would give you more than one row perobject_id
in the first case, and just one in the second, choosing the max among them.NOTE 2: These queries are standard SQL and should work not only on MySQL, but on most SQL RDBMS.
You can check everything at dbfiddle here