Reputation: 165
My country table has these columns: rank_id, and country_name.
Right now it's ordering by name, but I'm trying to put a few specific countries at the top of the list in their rank order, and then the rest to follow via name.
Here's my query:
foreach ($db->query("SELECT * FROM " . config_item('cart', 'table_countries') . "") as $row)
$countries[] = $row;
Any ideas?
Upvotes: 2
Views: 714
Reputation: 2780
If you add a rank_order
column with a default of 0
, and then change it to higher numbers for the few specific countries that you want at the top of the list.
You can then use this query to fetch your data:
SELECT * FROM table_countries ORDER BY rank_order DESC, country_name
Rows to be ordered by rank will always go first (in descending order), because their rank_order
is higher than 0
. The rest will be ordered alphabetically by country_name
.
Upvotes: 1
Reputation: 20853
A simple way of achieving this is to include a numerical display_order
column in country_name
that allows you to override the precedence set by ordering using name.
This would allow you to move countries arbitrarily to the top of the list based upon your needs and without having to alter queries at a later date.
You can then just do something like:
SELECT *
FROM country_name
ORDER BY display_order ASC, name ASC;
Upvotes: 0
Reputation: 19
You could tweak your "ORDER BY" clause by adding something like :
ORDER BY country_name='USA' DESC, country_name='Canada' DESC, country_name ASC
Since "country_name='USA'" returns "true" (or 1) only for USA and "false" (or 0) for all other countries and the order by is descending, USA would be first, then the same for Canada, then all others would come!
Upvotes: 1