2013-07-11 92 views
1

我有一個MySQL表由這些列中出現兩次:MySQL的選擇與同一列不同的where子句

USER_ID,開始,結束,區

每個用戶ID在開始和結束值各地區,像這樣:

+-----------------------------------+ 
| user_id | start | end | district | 
|  1 | 1000 | 2000 | north | 
|  1 | 1200 | 2200 | south | 
|  2 | 900 | 1900 | north | 
|  2 | 950 | 1700 | south | 
+-----------------------------------+ 

我要尋找一個選擇具有每USER_ID一行結果,其中列出了每兩個區的開始和結束。像

select user_id, 
(start as no_st, end as no_en where district='north'), 
(start as so_st, end as so_en where district='south'); 

東西給:

+-----------------------------------------+ 
| user_id | no_st | no_en | so_st | so_en | 
|  1 | 1000 | 2000 | 1200 | 2200 | 
|  2 | 900 | 1900 | 950 | 1700 | 
+-----------------------------------------+ 

是否有這種神奇的查詢?

感謝, 巴特......

+1

你有沒有做過任何研究或嘗試新鮮事物? – Quantastical

回答

0

這是一個支點查詢一個解決方案:

SELECT user_id, 
    MAX(IF(district='north', start, null)) AS no_st, 
    MAX(IF(district='north', end, null)) AS no_en, 
    MAX(IF(district='south', start, null)) AS so_st, 
    MAX(IF(district='south', end, null)) AS so_en 
FROM `NoOneEverNamesTheirTableInSQLQuestions` 
GROUP BY user_id; 
+0

比爾,你是一個天才 – user2573921