如何将SQL表中指定内容的行置顶后按id排序?
SQL Server指定行置顶后按ID排序
需求:将表中comment列值为my comment的行排在结果集最顶部,剩余行再按id列升序排列。
实现SQL语句:
SELECT * FROM 你的表名 ORDER BY CASE WHEN comment = 'my comment' THEN 0 ELSE 1 END, id ASC;
效果示例
排序前数据:
other comment other comment other comment my comment other comment my comment my comment
排序后结果:
my comment my comment my comment other comment other comment other comment other comment
原理:通过CASE语句给目标行分配更低的排序优先级(0),其他行优先级为1,确保目标行排在最前;之后按id升序完成剩余行的排序。
内容的提问来源于stack exchange,提问作者ryandra
相关产品推荐
相关产品推荐

