sql order by - Sort MySQL query ASC or DESC depending on value of other table -
i got query , want wort sort result depending on database.
this query:
select a.`name` `article` left join `container` b on b.`id` = a.`container` a.`container` = '1' order b.`sort` asc;
this works fine, sorts result ascending. bute want ist sorted depending on value in container table.
article table id | container | name | gender ---|---------------------|--------- 1 | 1 | michael | male 2 | 1 | joe | male 3 | 2 | karen | female 4 | 2 | andrew | male 5 | 3 | jessica | female container table id | sort | order ---|--------|---- 1 | name | asc 2 | name | desc 3 | gender | asc 4 | name | asc 5 | gender | desc
how can change query order container table?
i expect result:
id | container | name | gender ---|---------------------|--------- 2 | 1 | joe | male 1 | 1 | michael | male
you can't in 1 query.
a given sql query must fixed @ time prepare query, before execution begins. can't make behavior change depending on data discovers while executing.
you'll have read sort direction in 1 query, , format dynamic sql query values discover.
select `sort`, `order` container id = 1
fetch these data application variables $sort_column
, $direction
. use them:
$sql = " select a.`name` `article` a.`container` = '1' order {$sort_column} {$direction}"; ...prepare $sql query... ...execute query...
(i'm assuming php syntax variables, can similar in language.)
Comments
Post a Comment