2015-05-29 72 views
4

我有一個表QuotesTable - 主鍵是quotesid訂購where條款中指定的查詢結果

我有這個sql-statement

select * from QuotesTable where quotesid in (103,7,16,50,41,80,67,64) 

這將返回我結果按以下順序:

7 
16 
41 
......... 
103 and so on. 

,但我需要按以下順序結果作爲查詢(103規定, 7,16,50,41,80,67,64)爲:

103, 
7 
16 
....... 
64 and so on. 

有沒有辦法實現這個?

+0

你的桌子上是否有ID列反映了順序?或者可以考慮在表格中添加一個訂單列以獲取正確的訂單?什麼決定了隨機查找的順序? – FuzzyJulz

+0

id列是quotesid,它是主鍵。 – Venkat

+0

我不認爲你明白我的意思,你說你需要按順序'103,7,16,50,41,80,67,64'這是什麼意思?通常你會在你的數據庫中有一個訂單欄,這樣你就可以在這種情況下簡單地訂購。 – FuzzyJulz

回答

4

試試這個:

select * from QuotesTable where quotesid in (103,7,16,50,41,80,67,64) 
order by case quotesid when 103 then 1 
         when 7 then 2 
         when 16 then 3 
         when 50 then 4 
         when 41 then 5 
         when 80 then 6 
         when 67 then 7 
         when 64 then 8 
     end 

如果這些值增長,那麼你可以在數據庫中創建一個表:

create table QuotesOrderingTable(quotesid int, orderid int) 
go 

用適當的值填充它:

insert into QuotesOrderingTable values 
(103, 1), 
(7, 2), 
(16, 3), 
(50, 4), 
(41, 5), 
(80, 6), 
(67, 7), 
(64, 8), 
(..., 9), 
(..., 10), 
... 

,然後用它通過:

select qt.* from QuotesTable qt 
join QuotesOrderingTable qot on qt.quotesid = qot.quotesid 
where qt.quotesid in (103,7,16,50,41,80,67,64) 
order by qot.orderid 
+0

這工作,但不是其他解決方法,以實現相同的結果?如果我需要使用100條記錄,那麼查詢會變得很大不是? – Venkat

+0

@Venkat,這是最簡單的。你應該點菜。 –

+0

@Venkat: - 不,這應該是最簡單的! –

0

另一種選擇是做這樣的:

SELECT 1, * FROM QuotesTable WHERE quotesid = 103 UNION ALL 
SELECT 2, * FROM QuotesTable WHERE quotesid = 7 UNION ALL 
SELECT 3, * FROM QuotesTable WHERE quotesid = 16 UNION ALL 
SELECT 4, * FROM QuotesTable WHERE quotesid = 50 UNION ALL 
SELECT 5, * FROM QuotesTable WHERE quotesid = 41 UNION ALL 
SELECT 6, * FROM QuotesTable WHERE quotesid = 80 UNION ALL 
SELECT 7, * FROM QuotesTable WHERE quotesid = 67 UNION ALL 
SELECT 8, * FROM QuotesTable WHERE quotesid = 64 
ORDER BY 1 

不是最漂亮的,但ATLEAST你是不是重複WHERE子句

另一種變體,它看起來更好一點:

SELECT * FROM QuotesTable q 
JOIN (SELECT 1 ordering, 103 quotesid UNION ALL 
     SELECT 2   , 7 UNION ALL 
     SELECT 3   , 16 UNION ALL 
     SELECT 4   , 50 UNION ALL 
     SELECT 5   , 41 UNION ALL 
     SELECT 6   , 80 UNION ALL 
     SELECT 7   , 67 UNION ALL 
     SELECT 8   , 64) o ON o.quotesid = q.quotesid 
ORDER BY o.ordering 
+0

它會工作,你消除了重複的順序條款,但相反,你重複與工會選擇,這是更糟糕的。 –

+0

比較它會很有趣,因爲它沒有在物理表上選擇,並且你會假設QuotesTable中的行數遠遠大於8 – FuzzyJulz