2011-05-03 30 views
1

HI所有的底部,MySQL的選擇的id *,但地方陣列結果

,如果我做了select * from table ID列的輸出將是1,2,3,4,5,6,7 ,8,9 ...等。

有無論如何我可以做一個select * from table where id not in (3,6,9)然後在一個查詢select * from table where id in (3,6,9)所以輸出將像 1,2,4,5,7,8,10 .... 3,6,9 ???

謝謝。

編輯:

select * from table order by ts desc然後select * from table where id in (3,6,9)

+0

re:你的編輯:應該是? 'select * from table where id not in(3,6,9)order by ts desc' then'select * from table where id in(3,6,9)' – 2011-05-03 16:18:28

回答

1

什麼

select * from table where id not in (3,6,9) 
UNION ALL 
select * from table where id in (3,6,9) 
+0

+1對於使用'UNION ALL'而不是'UNION',因爲我認爲對於後者來說,每種機會都會出現以排除完全否定練習的重複。但我仍然認爲這在語義上是可疑的。優化器的未來版本應該可以自由地將該表達式重寫爲語義上等效的'select * from table where id is not null',因爲它沒有提到期望的最終順序,僅僅依賴於當前的實現。 – 2011-05-03 16:42:30

5
SELECT * 
FROM table 
ORDER BY CASE WHEN id in (3,6,9) THEN id ELSE 1 END 

回覆:您的編輯:

SELECT * 
FROM table 
ORDER BY CASE WHEN id in (3,6,9) THEN 1 ELSE 0 END ASC, ts DESC 
+0

ok假設我已經通過另一個字段排序表(時間戳),是否有按時間戳保留訂單,然後添加ID作爲他們? – 2011-05-03 16:07:22

+0

使用'union'替代。 – Johan 2011-05-03 16:08:53

+0

@Ranan,你的意思是說,在每個「部分」中,你想要'timestamp'排序的行嗎?如果是這樣,你可以使用'ORDER BY CASE WHEN ID(3,6,9)THEN 1 ELSE 0 END,timestamp' @Johan - 'UNION'不起作用。 'UNION'本身會導致重複排除。 'UNION ALL'可能會工作,但這只是依靠實施細節。 – 2011-05-03 16:10:08

0

你可以做

select * from table where id not in (3,6,9) 
union 
select * from table where id in (3,6,9) 
0

你可以使用一個UNION查詢:

SELECT ... 
UNION 
SELECT ...