2017-08-27 22 views
0

我有一個類似下面這個查詢的查詢。MySQL對ORDER做出例外?

SELECT name, id, note_date, note 
FROM example 
ORDER BY name, note_date 

假設我有一個名爲「John Smith」的用戶。我希望查詢能夠按原樣工作,除非我希望John Smith的所有條目違反命令並出現在列表頂部。

我只是想知道是否有一個更簡單或更正確的方法來做到這一點,而不是一個JOIN(如下圖)。

此外,如果它很重要,「約翰史密斯」在任何給定的時間可能會或可能不會有條目。

謝謝!

像:

SELECT name, id, note_date, note 
FROM example 
WHERE name = "John Smith" 
ORDER BY note_date 
JOIN 
SELECT name, id, note_date, note 
FROM example 
WHERE name != "John Smith" 
ORDER BY name, note_date 
+0

爲什麼使用JOIN這裏?聯盟似乎更合適。 – Mikhail

回答

2
SELECT name, 
      id, 
      note_date, 
      note, 
      CASE 
       WHEN name= 'John Smith' 
        THEN 0 
       ELSE 1 
       END AS OrderStatement 
FROM example 
ORDER BY OrderStatement, name, note_date 

只要你需要創建一個多列生成客戶訂單,並用它在ORDER BY子句與其他列一起。

+0

這很好。我很欣賞它,以及其他所有例子。感謝大家。 – Reno

0

您可以使用

情況下,當再

這樣我們

select id, etc, etc 
    case users.name 
     when ‘John Smith’ then ORDER BY etc 
     when 'X' then ORDER BY etc 
    end 
from`users` 

,請注意vorgoles,這些都不是正確的,但我爲我的手機上有沒有合適的人

0

一種方法是使用UNION:

(SELECT name, id, note_date, note 
FROM example 
WHERE name = "John Smith" 
ORDER BY note_date) 
UNION 
(SELECT name, id, note_date, note 
FROM example 
WHERE name != "John Smith" 
ORDER BY name, note_date) 

另一個更簡潔的方法是使用CASE操作:

SELECT name, id, note_date, note, CASE WHEN name='John Smith' THEN 1 ELSE 2 END as rank 
FROM example 
ORDER BY rank, name, note_date