在MySQL中指定GROUP BY

时间:2014-08-12 10:31:15

标签: mysql group-by

我有一张表格如下:

id   b_id   picture
---+------+----------------------
1  |   1  |     head.jpg
2  |   1  |     willson.jpg
3  |   1  |     babolat.jpg
4  |   2  |     head.jpg
5  |   2  |     prince.jpg
6  |   3  |     yonex.jpg
7  |   4  |     fila.jpg
8  |   2  |     brooks.jpg
9  |   0  |     sergio_tacchini.jpg
10 |   0  |     nike.jpg
11 |   0  |     lacoste.jpg
12 |   0  |     dunlop.jpg

现在我想要GROUP BY b_id,但仅限于b_id不是0。

输出必须如下:

id   b_id    picture
---+------+------------------------
1  | 1    |   head.jpg
4  | 2    |   head.jpg
6  | 3    |   yonex.jpg
7  | 4    |   fila.jpg
9  | 0    |   sergio_tacchini.jpg
10 | 0    |   nike.jpg
11 | 0    |   lacoste.jpg
12 | 0    |   dunlop.jpg

3 个答案:

答案 0 :(得分:0)

试试这个。

<强> QUERY

 (SELECT MIN(id) AS 'id',b_id,picture
 FROM table_name WHERE b_id >0
 GROUP BY b_id)
 UNION ALL 
 (SELECT id,b_id,picture
 FROM table_name WHERE b_id=0);

<强> FIND SQL FIDDLE HERE

答案 1 :(得分:0)

子查询每ID获得最小b_ID。为了获取其他列(在本例中为,只有一列),子查询的结果将连接到表本身,前提是它与b_id和最小值相匹配ID

SELECT  a.ID, a.b_id, a.picture
FROM    tableName a
        INNER JOIN
        (
            SELECT  b_id, MIN(a.id) min_id
            FROM    tableName
            GROUP   BY b_id
        ) b ON a.b_id = b.b_id
                AND a.ID = b.min_id

答案 2 :(得分:0)

结合Ullas和John Woo:

   SELECT a.id, 
          a.b_id, 
          a.picture
     FROM table_name a
LEFT JOIN (
       SELECT b_id, MIN(id) min_id
         FROM table_name
        WHERE b_id > 0
     GROUP BY b_id
          ) b 
       ON a.b_id = b.b_id
      AND a.id = b.min_id
    WHERE a.b_id = 0
       OR b.b_id IS NOT NULL

See Fiddle