I have five tables that are fairly similar in structure but different enough that I wanted to have them as separate tables. Essentially, the tables record events in five different “categories” that have some common fields and some other unique fields.
It now appears I need to write a report in which records from all five tables are shown in descending order of the record creation timestamp (standard across all tables). All tables have the common fields I need, things like fName, lName, scorePercent, numCorrect, etc.
I can’t seem to figure out the best way to write a query to select records from all five tables and display them in one table with a column showing the table from which the record came and the values for the common fields, ordered descending by datetime.
Is there any easy way to do this? Do I have to do it with PHP? I am starting to question my original design.
Thanks.
If the data is similar enough to be queried together, it’s probably similar enough to be stored together in one table with an extra column to record the type, however…
You could use a single where statement outside the inner query, but it would perform poorly, because all the rows of all the tables would be unioned. This way, only the rows actually needed are unioned.
Note that
UNION ALLis a better choice thanUNION, becauseUNION ALLdoesn’t sort (withUNIONthe data would be sorted twice – once to remove duplicates and again for the order by).