php - Order one table based on column of another using MySQL -
i trying implement join can order results of 1 table based on column of table. sql works when records exists in both tables. sql works when there more records in table1 there in table2, providing not use order by
clause.
sql:
select * table1 join table2 b on table1.col1 = b.col1 col3 != 0 order b.col2 asc;
table 1
col1 | col2 | col3 __________________ 1 foo 1 2 foo 1 5 foo 1 9 foo 0 10 foo 1 17 foo 0 14 foo 1 12 foo 1
table 2
col1 | col2 ___________ 1 2 b 17 e 14 g 12 l
the part of query order b.col2 asc
causing fail when records between 2 tables not matching.
i cannot guarantee record present in both. there way of still implementing this?
i using mysqli
can use pdo
if needed.
like @maximus2012 mentioned, try left join
. give of records table1 , records table2 match col1 table1.
select * table1 left join table2 b on table1.col1 = b.col1 col3 != 0 order b.col2 asc
if looking records table2 , match table 1, use right join
instead.
select * table1 right join table2 b on table1.col1 = b.col1 col3 != 0 order b.col2 asc
Comments
Post a Comment