MySQL group by with rollup的用法

發表于:2013-07-24來源:OurMySLQ作者:OurMySLQ點擊數: 標簽:MySQL
有一位同學通過askdba來詢問with rollup的用法 (2012-02-01 15:08:22): mysql中有這種用法select … from table_name group by a with rollup

  有一位同學通過askdba來詢問with rollup的用法

  (2012-02-01 15:08:22):

  mysql中有這種用法select … from table_name group by a with rollup

  “with rollup”是什么意思呢?

  GROUP BY Modifiers 官方手冊里面對這個rollup有一個專門的頁面介紹 地址在這里,說得非常詳細,我這里做一個簡單的例子重現

  建一個簡單的表并插入幾條簡單的數據

  CREATE TABLE `t` (

  `id` int(11) DEFAULT NULL,

  `id2` int(11) DEFAULT NULL

  ) ENGINE=InnoDB DEFAULT CHARSET=gbk

  insert into t valeu(11,11),(12,12),(13,13);

  先來做一個查詢

  root@test 03:44:32>select id,sum(id2),avg(id2) from t group by id with rollup;

  +——+———-+———-+

  | id | sum(id2) | avg(id2) |

  +——+———-+———-+

  | 11 | 11 | 11.0000 |

  | 12 | 12 | 12.0000 |

  | 13 | 13 | 13.0000 |

  | NULL | 36 | 12.0000 |

  +——+———-+———-+

  4 rows in set (0.00 sec)

  我們可以看到,對于group by的列,with rollup將不會做任何的操作,而是返回一個NULL,而沒有group by的列,則根據前面的avg函數和sum函數做了處理。

  再來看另外一個語句,只對一個列做avg

  root@test 03:44:36>select id,avg(id2) from t group by id with rollup;

  +——+———-+

  | id | avg(id2) |

  +——+———-+

  | 11 | 11.0000 |

  | 12 | 12.0000 |

  | 13 | 13.0000 |

  | NULL | 12.0000 |

  +——+———-+

  4 rows in set (0.00 sec)

  以前從沒留意到有這種用法,這次長見識了。

原文轉自:http://ourmysql.com/archives/1144

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97