Using union and order by clause in mysql
You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:
You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:
You can provide a custom ordering, then take the first row, like this: Explanation: The inner select’s order by field(LOCALE, ‘ge’, ‘_’) gets you the rows in the order you define – in this case German first if it exists, then English (you could add more languages to the list). The “trick” here is using mysql’s “non-standard” GROUP … Read more
Put the columns names explicitly rather than *, and make sure the number of columns and data types match for the same column in each select. Update: I really don’t think you want to be UNIONing those tables, based on the tables names. They don’t seem to contain related data. If you post your schema … Read more
Just write the order by is applied to the complete resultset
UNION puts lines from queries after each other, while JOIN makes a cartesian product and subsets it — completely different operations. Trivial example of UNION: similary trivial example of JOIN:
UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not. There is a performance hit when using UNION instead of UNION ALL, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports). UNION Example: Result: UNION ALL example: Result: