MySQL BY语句在GROUP BY中

时间:2014-07-31 07:59:55

标签: mysql sql

我有下表:

| id | msgType | user | job_id | project_id |
|+++++++++++++++++++++++++++++++++++++++++++|
| 1  | 1       | 1    | 1      | 1          |
| 2  | 1       | 1    | 2      | 1          |
| 3  | 2       | 1    | 3      | 1          |
| 4  | 2       | 1    | 4      | 1          |
| 5  | 1       | 1    | 5      | 2          |

我的查询:

SELECT msgType ,user, job_id, project_id 
FROM mail
GROUP BY msgType,user,project_id,job_id

此查询的输出:

| msgType | user | job_id | project_id |
|++++++++++++++++++++++++++++++++++++++|
| 1       | 1    | 1      | 1          |
| 1       | 1    | 2      | 1          |
| 2       | 1    | 3      | 1          |
| 2       | 1    | 4      | 1          |
| 1       | 1    | 5      | 2          |

我想要的输出是:

| msgType | user | job_id | project_id |
|++++++++++++++++++++++++++++++++++++++|
| 1       | 1    | 1      | 1          |
| 2       | 1    | 3      | 1          |
| 2       | 1    | 4      | 1          |
| 1       | 1    | 5      | 2          |

所以基本上if msgType = 1然后我想在每个不同的project_id if msgType=2中为每个用户看到1行,然后我想在“项目”中看到每个job_id

非常感谢任何帮助。

更新

我为此创造了一个小提琴:

http://sqlfiddle.com/#!2/5708b8/4

3 个答案:

答案 0 :(得分:1)

试试这个

   SELECT * FROM
   (
    SELECT msgType ,user, job_id, project_id 
    FROM mail
    WHERE msgType = 1
    GROUP BY msgType,user,project_id,job_id

    UNION ALL

    SELECT msgType ,user, job_id, project_id 
    FROM mail
    WHERE msgType <> 1
   )T ORDER BY T.msgType Desc

Bohemian 一样,您不能在不使用任何Group BY的情况下使用aggregate functions

如果您想获得所需的结果,那么您必须使用如下所示的查询,但不完全是

   SELECT * FROM
   (
    SELECT msgType ,user, MIN(job_id), project_id
    FROM mail
    WHERE msgType = 1
    GROUP BY msgType,user, project_id

    UNION ALL

    SELECT msgType ,user, job_id, project_id 
    FROM mail
    WHERE msgType <> 1
   )T ORDER BY T.msgType Desc

答案 1 :(得分:1)

   SELECT * FROM
   (
     SELECT msgType ,user, min(job_id), project_id 
     FROM mail
     WHERE msgType = 1
     GROUP BY msgType,user,project_id

     UNION ALL

     SELECT msgType ,user, job_id, project_id 
     FROM mail
     WHERE msgType <> 1

   )T ORDER BY T.msgType Desc

在这里小提琴:http://sqlfiddle.com/#!2/5708b8/7

答案 2 :(得分:1)

要在一个声明中完成所有操作,您可以这样做:

http://sqlfiddle.com/#!2/5708b8/16

SELECT msgType
, min(user) user
, min(job_id) job_id
, project_id
FROM mail
group by msgType
, project_id
, case when msgType = 1 then user else job_id end

虽然我怀疑上面的union all方法更容易理解,但从可维护性的角度来看可能会更好。