2014-07-24 137 views
0

我正在嘗試執行類似於this question的操作。我有這個表:語法不正確'='

<code>tab_id</code> is the second column. <code>order_in_tab</code> is the fourth column.

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

我要訂購tab_id等於2先,然後再按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新手,所以我不確定什麼是錯的(或者如果我誤解了上面的鏈接解決方案)。

+2

確定此「按(tab_id ='2')排序」可以工作嗎?從未在目前的訂單中看到過「=」 – Thomas

+0

您正在使用哪個數據庫? –

+1

你想用'(tab_id ='2')'來實現什麼? –

回答

3

嘗試改變這樣的查詢:

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 
+0

關閉... ASC應該不是DESC,因爲他首先需要這些?或者只是在case語句中切換1和0。 – xQbert

+0

沒錯,感謝您的注意。我會更新答案 – dotnetom

+1

你能詳細解釋'CASE WHEN tab_id ='2'那麼1 ELSE 0 END DESC'部分嗎? –

1

我想你在查詢中有一個複製粘貼&錯誤。

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 
+0

我犯了同樣的錯誤OP post說:「我想按tab_id等於2首先,其餘的tab_id升序,然後order_in_tab升序。「 – xQbert

0

爲了通過你不能指定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在默認情況下,如果你不指定任何東西。

+0

你可以這樣做。看到我的答案。 –

1

您鏈接的問題是正確的。你只是錯過了字段的類型。它有一個字符串字段可以被均衡爲一個字符串。

所以你的情況,你所要做的,因爲這:

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將使ID與第2的結果。

見這裏的小提琴:http://sqlfiddle.com/#!2/15ffc/2

編輯:

的任擇議定書表示,它是使用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 
+0

它仍在抱怨他= =標誌 –

+0

@Cyber​​neticTwerkGuruOrc那麼你的RDBM是什麼? Mysql,Oracle,Postgre MSSql? –

+0

我正在通過Microsoft SQL Server Management Studio執行此操作 –