2011-11-12 163 views
0

後做一些連接和東西,我有表的格式如下問題與MySQL GROUP_CONCAT

name session_id status 
    abc   1   null  
    xyz   2   11   
    jack  2   10 
    zuck  1   10 
    paul  1   10 

我想我的結果是這樣

session_id name+status     
    1   abc:-1, zuck:10, paul:10 
    2   xyz:11, jack:11 

分組所以我用MySQL的GROUP_CONCAT在SQL像

SELECT sr.avail_id AS id,sr.student_id, sa1.punctuality_status as associate_punctuality_status, IF(
        (sa.punctuality_status IS NULL), 
        (group_concat(u.firstname, ' ', u.lastname, ':', '-1'), 
        (group_concat(u.firstname, ' ', u.lastname, ':', sa.punctuality_status) 
        ), 
        sr.tutor_id AS associate_id, FROM_UNIXTIME(sr.timestart) AS timestart, 
        sr.session_id AS session_id, sr.type AS session_type, p.name AS program_name, 
      m.name AS module_name, ms.name AS session_name, sr.status as session_status FROM mdl_session_requests AS sr 
     LEFT JOIN mdl_session_attendee AS sa ON (sr.student_id = sa.user_id AND sr.session_id = sa.session_id) 
     LEFT JOIN mdl_session_attendee AS sa1 ON (sr.tutor_id=sa1.user_id and sr.session_id=sa1.session_id) 
     INNER JOIN mdl_module_session ms ON ms.id = sr.course_id  
     INNER JOIN mdl_module m ON m.id = ms.module_id 
     INNER JOIN mdl_program p ON p.id = m.program_id 
     INNER JOIN mdl_user u ON u.id = sr.student_id  
     WHERE sr.tutor_id =438 group by avail_id order by sr.timestart desc 

error =「#1064 - 您的SQL語法有錯誤;請檢查對應的手冊到您的MySQL服務器版本的正確語法使用附近'AS associate_id,FROM_UNIXTIME(sr.timestart)AS timestart,sr.session_id AS'在第6行「

這個SQL有什麼問題嗎?

+3

*「有些錯誤」*?你遇到了什麼錯誤? –

+0

您的SQL語法錯誤;檢查對應於你的MySQL服務器版本的手冊,在'AS tutor_id'附近使用正確的語法。 – user401445

+1

似乎缺少「from」子句。 – MatTheCat

回答

2
SELECT 
    s.session_id AS id, 
    group_concat(SEPARATOR ', ' CONCAT(u.firstname, ' ', u.lastname, ':',IF(s1.status IS NULL,'-1',s1.status))), sr.tutor_id 

FROM [a table] 
GROUP BY session_id 

問題:

  1. 沒有形成where子句中不匹配
  2. GROUP_CONCAT可以在一個領域做到,所以你需要CONCAT()所有的值第一
  3. parentesis。
+0

這不是實際的sql ...只是一個抽象...我已更新問題 – user401445

+0

使用我的示例來修改您的查詢 –

+0

工作就像一個魅力......但我仍然困惑以前的查詢中的問題是什麼? – user401445