I have a select statement returning 5 columns:
select col1,col2,col3,col4,col5 from table1;
col1 col2 col3 col4 col5
9 A B C D
8 E F G H
I have another select statement from table2 which returns col1 alone;
col1
8
9
Based on the two select queries, is there a way to write a single select query to return the result as:
col1 col2 col3 col4 col5
8 E F G H
9 A B C D
ie. basically sort the output of I query based on col1 from II query. (this is in Mysql)
PS:II table column1 is used to for sorting & that is coming from table 2. Table2’s col1 is not static, its changing for every user action & based on a call i will get col1 of table 2 & need to sort with table1’s output.
For this to work, you
seriouslyneed asortcolumn on table2. Just having the IDs in table2 is not enough. You can have the records 7,8,9, then delete 8 and add it back. But no, that doesn’torderit as 7,9,8. Maybe temporarily if there is no primary key on the table, but when the table gets large, even that “implicit” order is lost.So, assuming you have such a sort column
Your query becomes
If you still want to rely on MySQL undocumented features or the way it currently works, then you can try this.
This works at least for small tables, only because size(table2) < size(table1) so it collects in that order, preserving the filesort on table2.col1.