按特定列或字母顺序进行排序查询 - Coldfusion

5
我们有一个 ColdFusion 网站,它检索我们的分类,然后按字母顺序显示它们。
我们希望能够通过手动排列具有数字“排序”列的类别来强制排序,但如果该数字等于 0 或 null,则使用字母顺序。
因此,目前的查询为:
<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>

如果我尝试,它会起作用

ORDER BY thrdctgry_Sort ASC

但是我实在无法将它们连接起来,主要是因为我缺乏程序员的技能。

非常感谢您提供任何建议。


所以你想按 thrdctgry_Sort 进行排序,但如果它为零或为空,则希望按 thrdctgry_Name 进行排序? - Taryn
如果我们明确设置了排序顺序,它将遵循数字位置,对于其他任何内容,它将按字母顺序排列。 - matthew
3个回答

7
我可能对问题有所误解,但您应该能够在两个列上进行排序:
ORDER BY thrdctgry_Sort ASC, thrdctgry_Name ASC

2

这是带有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

对于排序,您可以在ORDER子句中使用CASE语句。

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

说实话,我没完全理解你的排序顺序,但你可以再尝试一下。

嗨,Muhammed,感谢您的帮助。不过在我做出这些更改后,我遇到了404错误,请看完整的查询语句 -:<cfquery name="qGetThrdCat" datasource="#request.dsn#"> 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 order by case when isnull(thrdctgry_Sort, 0) = 0 then thrdctgry_Name else thrdctgry_Sort end asc</cfquery> - matthew
你是指HTTP错误404吗?你能在你的SQL数据库中检查一下这个查询吗?你使用的是哪种数据库引擎? - Farhan
谢谢Muhammed,但我在数据库中尝试了这个,但它没有起作用,可能是因为我的编程知识有限! - matthew

0
<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
<cfif isNumeric(thrdctgry_Sort) and thrdctgry_Sort GT 0>
ORDER BY thrdctgry_Sort
<cfelse>
ORDER BY thrdctgry_Name ASC
</cfif>

使用SQL是最好的选择,但如果Muhammad Ghazi的解决方案不起作用,您可以使用服务器端代码来解决问题。


感谢您的建议,但“cfif”查询导致了404错误。 - matthew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接