I am trying to order myTable1
based on a column
in myTable2
. I have tried this using all kinds of joins
, for example right
,left
,inner
and just join
on it's own. The two following SQL queries have got me the closest the the end goal but they still aren't right. The following query correctly selects all the correct records but does not display them in the desired order. They are simply being output on the order they are stored within myTable1
SELECT myTable1.* FROM myTable1 INNER JOIN myTable2 b ON myTable1.myRef = b.myRef WHERE col2 = 1 ORDER BY b.col3 ASC
The following query correctly orders the records according to col2
within myTable2
but for some reason it only returns some of the results, not all of them.
SELECT myTable1.* FROM myTable1 LEFT JOIN myTable2 b ON myTable1.myRef = b.myRef WHERE col2 = 1 ORDER BY b.col3 ASC
For the record i'm using mysqli
Try the following:
SELECT myTable1.* FROM myTable1 JOIN (SELECT myTable2.* FROM myTable2) b ON myTable1.myRef = b.myRef WHERE col2 = 1 ORDER BY b.col3 ASC
If your WHERE statement is referecing col2 correctly, this approach should work just fine.