繁体   English   中英

“ =”处的语法不正确

[英]Incorrect syntax at '='

我正在尝试做与此问题类似的事情。 我有这张桌子:

<code> tab_id </ code>是第二列。 <code> order_in_tab </ code>是第四列。

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

我想tab_id等于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 '='.表示Incorrect syntax at '='. 我是一名完全的SQL新手,所以我不确定什么地方出了问题(或者我是否误解了上面的链接解决方案)。

尝试像这样更改查询:

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

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

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

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

因此,在您的情况下,您必须这样做:

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放在结果上。

在小提琴上看到它: 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

您不能按顺序指定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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM