Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by query using specific column or alphabetical. - Coldfuison

we have a coldfusion website that retrieves our categories then displays them alphabetically.

We would like to be able to force an order by manually arranging the categories with a 'sort' column with a number in but if this number is equal to 0 or null use alphabetical order.

so at the moment the query is

<cfquery name="qGetThrdCat" datasource="#request.dsn#">
    SELECT *
    FROM tbl_prdtthrdcats, tbl_scnd_thrdcat_rel
    WHERE tbl_scnd_thrdcat_rel.thrdctgry_ID = tbl_prdtthrdcats.thrdctgry_ID
    AND tbl_scnd_thrdcat_rel.scndctgry_ID = #URL.secondary#
    AND thrdctgry_archive = 0
    ORDER BY thrdctgry_Name ASC
</cfquery>

It works if I try

ORDER BY thrdctgry_Sort ASC

but I can't for the life of me join them up, mainly down to my lack of programmer skills.

Any advice would be greatly appreciated.

like image 741
matthew Avatar asked Aug 16 '12 14:08

matthew


People also ask

How do you sort a query in alphabetical order?

Enter ORDER BY criteria; . For example, if you wanted to display results in alphabetical order based on a column called NAME, you'd use ORDER BY NAME; . Ascending order is the default sort order, but you could also specify that you want it ascending using ORDER BY NAME ASC; if you'd like.

How do I arrange a column in alphabetical order in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you write a query for ORDER BY?

Syntax. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause.

Can you query columns in any order?

The order doesn't matter, actually, so you are free to order them however you'd like. edit: I guess a bit more background is helpful: As far as I know, the process of optimizing any query happens prior to determining exactly what subset of the row data is being pulled.


2 Answers

I may be misunderstanding the question, but you should be able to just sort on both columns:

ORDER BY thrdctgry_Sort ASC, thrdctgry_Name ASC
like image 183
Sean Walsh Avatar answered Sep 25 '22 00:09

Sean Walsh


Here is your query with join:

select *
from tbl_prdtthrdcats p
join tbl_scnd_thrdcat_rel s
    on p.thrdctgry_ID = s.thrdctgry_ID
where
    s.scndctgry_ID = #URL.secondary# 
and thrdctgry_archive = 0

For the sorting, you can use CASE in your ORDER clause.

order by
case
    when isnull(thrdctgry_Sort, 0) = 0
    then thrdctgry_Name
    else thrdctgry_Sort
end asc

To be honest, I couldn't understand your sorting order completely, but you can play around with it more.

like image 41
Farhan Avatar answered Sep 25 '22 00:09

Farhan