【问题标题】:Incorrect syntax at '=''=' 处的语法不正确
【发布时间】:2014-09-16 12:19:35
【问题描述】:

我正在尝试做类似于this question 的事情。我有这张桌子:

tab_id 是第二列。 order_in_tab 是第四列。

我想先按等于2tab_id 排序,然后将其余的tab_id 升序,然后order_in_tab 升序。

select * 
from cam_to_tab_mapping 
where unit_id='90013550' 
order by (tab_id='2') asc, tab_id asc, order_in_tab asc

但是,它显示Incorrect syntax at '='.。我是一个完整的 SQL 新手,所以我不确定出了什么问题(或者我是否误解了上面的链接解决方案)。

【问题讨论】:

  • 确定这个“order by (tab_id='2')”可以工作吗?到目前为止,从未见过“=”的顺序
  • 您使用的是哪个数据库?
  • 你想用 (tab_id='2') 达到什么目的?
  • 我犯了同样的错误 OP 帖子说:“我想先按等于 2 的 tab_id 排序,然后其余的 tab_id 升序,然后 order_in_tab 升序。”
  • 查看我的回答@Cyber​​neticTwerkGuruOrc,它显示了您误解的内容。

标签: sql sql-server


【解决方案1】:

尝试像这样更改查询:

select * 
from cam_to_tab_mapping 
where unit_id='90013550' 
order by CASE WHEN tab_id='2' THEN 1 ELSE 0 END DESC, tab_id asc, order_in_tab asc

【讨论】:

  • 关闭... ASC 不应该是 DESC,因为他首先想要那些?或者只是在case语句中切换1和0。
  • 您能详细解释一下CASE WHEN tab_id='2' THEN 1 ELSE 0 END DESC 部分吗?
  • 此语句表示计算值。如果 tab_id='2' 则计算值为 1,否则为 0。然后根据这个计算值进行排序
  • 我认为“order by CASE WHEN tab_id='2' THEN -1 ELSE tab_id END ASC, order_in_tab ASC”是他要求的解决方案。
  • @dotnetom 0不会放在1之前(参考then 1 else 0部分)?还是 SQL 不能那样工作?
【解决方案2】:

我认为您的查询中有复制和粘贴错误。

select * 
from cam_to_tab_mapping 
where unit_id='90013550' 
order by (tab_id='2') asc, tab_id asc, order_in_tab asc

您有一个逻辑表达式作为第一个 order by 条件。

也许你的意思

select * 
from cam_to_tab_mapping 
where unit_id='90013550' and tab_id='2'
order by tab_id asc, order_in_tab asc

【讨论】:

  • 我犯了同样的错误 OP 帖子说:“我想先按等于 2 的 tab_id 排序,然后其余的 tab_id 升序,然后 order_in_tab 升序。”
【解决方案3】:

您链接的问题是正确的。您只是误解了字段的类型。那里有一个字符串字段,可以等于一个字符串。

所以在你的情况下,你必须这样做:

select * 
 from cam_to_tab_mapping 
where unit_id='90013550' 
order by (tab_id=2) DESC, 
        tab_id asc, order_in_tab asc

(tab_id=2) DESC 会将 2 的 id 放在结果中。

在 fiddle 上看到它:http://sqlfiddle.com/#!2/15ffc/2

编辑:

OP 说它正在使用 SQL Server。这个答案适用于 MySQL。在 SQL SERVER 上,正确的方法是使用 CASE 语句,例如:

select * 
 from cam_to_tab_mapping 
where unit_id='90013550' 
order by (case when tab_id=2 then 0 else 1 end), 
        tab_id, order_in_tab

【讨论】:

  • 还在抱怨他=sign
  • @Cyber​​neticTwerkGuruOrc 那么您的 RDBM 是什么? Mysql、Oracle、Postgre MSSql?
  • 我正在通过 Microsoft SQL Server Management Studio 执行此操作
  • 那你不能这样做。是不是Mysql语句。您应该使用@dotnetom 提供的答案,因为 sql server 不支持这个。
【解决方案4】:

按顺序你不能指定tab_id=2。您必须添加另一个虚拟字段,其中 tab_id=2 为 0,否则为 1,并首先按该字段排序,然后按 tab_id。试试这个方法...

select mac, tab_id, unit_id, order_in_tab, 
(case when tab_id='2' then 0 else 1 end) as temp
from cam_to_tab_mapping 
where unit_id='90013550' 
order by temp, tab_id, order_in_tab

你(可以但)不需要在order by子句中指定asc,如果不指定,默认为asc。

【讨论】:

  • 你可以这样做。看我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
相关资源
最近更新 更多