2017-09-16 106 views
0

msyql查詢爲什麼我得到的MySQL結果列值dismatch

SELECT id,student_user_id,MIN(start_time) FROM appoint_course 
WHERE student_user_id IN(
    931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507, 
    2518,2594,2596,2600,2608,2637,2652,2654 
) 
AND course_type=3 and disabled=0 GROUP BY student_user_id; 

結果 [查詢結果]

+-------+-----------------+-----------------+ 
| id | student_user_id | MIN(start_time) | 
+-------+-----------------+-----------------+ 
| 8356 |    931 |  1500351000 | 
| 9205 |   2034 |  1501733400 | 
| 9246 |   2068 |  1501649100 | 
| 9755 |   2111 |  1502943000 | 
| 9585 |   2115 |  1502595300 | 
| 10820 |   2173 |  1503545700 | 
| 9594 |   2181 |  1502852400 | 
| 10324 |   2285 |  1502852400 | 
| 11204 |   2500 |  1504839600 | 
| 11152 |   2507 |  1504064100 | 
| 12480 |   2594 |  1505707800 | 
| 11521 |   2608 |  1504494000 | 
| 11818 |   2652 |  1504753200 | 
+-------+-----------------+-----------------+ 

但正確的開始時間爲:

id: 9594 
start_time: 1503284400 

9594右START_TIME是1503284400沒有1502852400.In其實1502852400是9597 記錄,我不知道爲什麼。

+1

你好湯姆。請閱讀[這](https://stackoverflow.com/help/how-to-ask)和改善你的問題,使人們可以來幫您吧。 – Jeffrey

+0

你的問題還不清楚。請向我們展示樣本輸入數據和您期望的輸出。 –

+0

START_TIME dismatch主要id.eg.right記錄:START_TIME:1,ID:1,但我得到START_TIME:1,ID:2 – Tom

回答

2

在任何其他數據庫查詢將返回一個錯誤,因爲id不在group by。正確的查詢是:

SELECT student_user_id, MIN(start_time) 
FROM appoint_course 
WHERE student_user_id IN (931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,2518,2594,2596,2600,2608,2637,2652,2654) AND 
     course_type = 3 and disabled = 0 
GROUP BY student_user_id; 

在你的情況下,添加一個簡單的MIN(id)SELECT可能工作,假設id s的啓動時間的增加。

更一般地,你會想:

SELECT ac.* 
FROM appoint_course ac 
WHERE ac.student_user_id IN (931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,2518,2594,2596,2600,2608,2637,2652,2654) AND 
     ac.course_type = 3 AND ac.disabled = 0 AND 
     ac.start_time = (SELECT MIN(ac2.start_time) 
         FROM appoint_course ac2 
         WHERE ac2.student_user_id = ac.student_user_id AND 
          ac2.course_type = ac.course_type AND 
          ac2.disabled = ac.disabled 
        ); 

沒有GROUP BY是必要的。

我要補充一點,有一個MySQL黑客經常工作:

SELECT student_user_id, MIN(start_time), 
     SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY start_time), ',', 1) as id_at_min_start_time 
FROM appoint_course 
WHERE student_user_id IN (931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,2518,2594,2596,2600,2608,2637,2652,2654) AND 
     course_type = 3 and disabled = 0 
GROUP BY student_user_id; 

這使用字符串操作和GROUP_CONCAT()可以溢出內部緩衝區大小。

+0

我沒有錯誤,但結果是不是做一些 – Tom

+0

好的我需要ID @湯姆。 。 。哪些不會產生您期望的結果?所有應該返回與每個學生用戶的最小開始時間相關的'id'。 –

+0

子查詢工作正常,謝謝you.I'll嘗試group_cat – Tom

相關問題