Search code examples
mysqlaliasfilemaker

Shortcut for aliasing many columns on multiple joins?


My first mySQL project.

I am migrating a FileMaker DB to mySQL and having trouble with how to efficiently handle duplicate field (column) names from 3 left joined tables, combined with the fact that each table is supplying a large number of columns (50+). I understand the concept of aliasing columns. Is there a better way than to create several hundred alias lines to handle each column from each table? I've searched the site and not found a discussion of handling a large number of columns, which is common in FileMaker DBs...perhaps not in mySQL.

Current code is below, where I created the aliases for only ONE (WebPublish) of the ~50 fields for each of the 3 joined tables:

$query = "SELECT

Artwork.WebPublish as Artwork_WebPublish,
Artist.WebPublish as Artist_WebPublish,
Location.WebPublish as Location_WebPublish

FROM Review 

LEFT JOIN Artwork ON Review._kf_ArtworkID = Artwork.__kp_ArtworkID 
LEFT JOIN Artist ON Review._kf_ArtistID = Artist.__kp_ArtistID 
LEFT JOIN Location ON Review._kf_LocationID = Location.__kp_LocationID  

WHERE __kp_ReviewID = ?";

This query produces the desired response for one column from each joined table:

Array
(
    [Artwork_WebPublish] => Yes
    [Artist_WebPublish] => No
    [Location_WebPublish] => Maybe
)

The question is whether I need to expand the aliases the long way to include 49 times more data.

Thanks for you help.


Solution

  • No, there's no SQL syntax for giving column aliases in a "batch" mode, for example applying the table name as a prefix to all columns (by the way, SQLite does support that feature by default).

    One way to solve this is to refer to columns by ordinal position instead of by name, in whatever language you use to fetch the results.

    Another solution is to define your tables with distinct column names so you avoid the name conflict. Some SQL identifiers, for example constraint names, are already required to be unique within the database they reside in, not only unique within a table. It may be a naming convention you want to use to apply the same rule to column names.