2011-10-28 60 views
5

我有一個像表:SQL - ORDER BY語句

table A 
id name email 
1 test1 [email protected] 
2 test2 [email protected] 
3 test3 [email protected] 
4 test4 .... 
5 test5 .... 

table B 
id catA catB year member 
1 false true 2011 2 
2 true false 2011 3 
3 fals true 2010 5 

而且我想每一行表A,並按照排序是:

FIRST, get user 2 (current year, based on table B) 
SECOND, get user 3 (current year, based on table B) 
after that get users that is in table B 
after that get all other users. 

我知道我可以有獲得前兩個用戶的具體sql,以及剩下的僅僅是 。但不應該我能夠得到他們所有與一個很好的ORDER的聲明?像限制一階聲明只是影響第一行...

+1

如果你有問題的答案,請接受它。 –

回答

4

是這樣的?

select A.id, A.name, A.email, B.catA, B.catB, B.year 
from A 
join B on A.id = B.member 
ORDER BY B.year DESC, (B.member IS NOT NULL) DESC 

首先排序的所有結果由表B中一年字段,它讓你2011,2010,等等...誰不表B中列出的所有成員將有一個空的一年和排序,以底部列表。接下來按B.member排序不爲null - mysql會強制將此布爾結果轉換爲可以排序的整數1或0,所以按降序排序以使所有1(非空B.members)排序。

+0

最近明白了: ORDER BY(tableb.year IS NULL)ASC,(tableb.member IS NOT NULL)DESC。 得到它最正確的,現在的問題是,我想先得到B.catA,然後B.catB。並且如果可能的話,我只想要catA和catB中的最新版本,然後訂單無關緊要... – joxxe

+0

修正了它: ORDER BY(CASE tableB.year當提取(從現在開始的年份)然後0 ELSE 1 END)ASC,tableA.id desc; – joxxe

0

根據您的排序規則:

after that get users that is in table B 
after that get all other users. 

我假設有表A中一些用戶沒有B中存在,所以你要使用LEFT JOIN。

SELECT a.id, a.name, a.email 
    FROM a 
     LEFT JOIN b 
      ON a.id = b.member 
    ORDER BY ISNULL(b.year), b.year DESC, a.name 
0

你總是可以「按訂單」,然而荒唐複雜的選擇是,買把數據收集元素融入派生表,從中選擇和排序的結果。喜歡的東西...

SELECT col1, 
     col2, 
     col3 
    FROM 
     (SELECT 1 as col1, 
       col2, 
       ' ' AS col3 
      FROM blah...blah...blah 
      UNION 
     SELECT 2 AS col1 
       col2, 
       col3 
      FROM blah...blah...blah 
      UNION 
     and so on) myderivedtable 
    ORDER BY col1, 
      col2, 
      col3 

你一定要確保所有列您選擇在每個查詢出來的一樣,或者與NULL值應對。