关键词搜索

源码搜索 ×
×

mysql distinct 和 group by

发布2017-10-19浏览7214次

详情内容

         刚好用到, 记录一下, 表为:

  1. mysql> select * from t1;
  2. +----+------+-----+---------------------+
  3. | id | name | age | tt |
  4. +----+------+-----+---------------------+
  5. | 30 | n1 | 10 | 2017-10-19 10:28:23 |
  6. | 31 | n1 | 10 | 2017-10-19 10:28:42 |
  7. | 32 | n1 | 15 | 2017-10-19 10:28:53 |
  8. | 33 | n2 | 15 | 2017-10-19 10:29:03 |
  9. +----+------+-----+---------------------+
  10. 4 rows in set (0.00 sec)

       找name:

mysql> select name from t1;
+------+
| name |
+------+
| n1   |
| n1   |
| n1   |
| n2   |
+------+
4 rows in set (0.00 sec)
       

       去重找name:

  1. mysql> select distinct name from t1;
  2. +------+
  3. | name |
  4. +------+
  5. | n1 |
  6. | n2 |
  7. +------+
  8. 2 rows in set (0.01 sec)
  1. mysql> select count(distinct name) from t1;
  2. +----------------------+
  3. | count(distinct name) |
  4. +----------------------+
  5. | 2 |
  6. +----------------------+
  7. 1 row in set (0.01 sec)

        去重找(name, age)的组合:

  1. mysql> select distinct name, age from t1;
  2. +------+-----+
  3. | name | age |
  4. +------+-----+
  5. | n1 | 10 |
  6. | n1 | 15 |
  7. | n2 | 15 |
  8. +------+-----+
  9. 3 rows in set (0.01 sec)
  1. mysql> select count(distinct name, age) from t1;
  2. +---------------------------+
  3. | count(distinct name, age) |
  4. +---------------------------+
  5. | 3 |
  6. +---------------------------+
  7. 1 row in set (0.00 sec)


       用上group by:

  1. mysql> select * from t1 group by name;
  2. +----+------+-----+---------------------+
  3. | id | name | age | tt |
  4. +----+------+-----+---------------------+
  5. | 30 | n1 | 10 | 2017-10-19 10:28:23 |
  6. | 33 | n2 | 15 | 2017-10-19 10:29:03 |
  7. +----+------+-----+---------------------+
  8. 2 rows in set (0.00 sec)
  1. mysql> select count(*) from t1 group by name;
  2. +----------+
  3. | count(*) |
  4. +----------+
  5. | 3 |
  6. | 1 |
  7. +----------+
  8. 2 rows in set (0.00 sec)
  1. mysql> select name, count(*) from t1 group by name;
  2. +------+----------+
  3. | name | count(*) |
  4. +------+----------+
  5. | n1 | 3 |
  6. | n2 | 1 |
  7. +------+----------+
  8. 2 rows in set (0.00 sec)
  1. mysql> select name, age, count(*) from t1 group by name, age;
  2. +------+-----+----------+
  3. | name | age | count(*) |
  4. +------+-----+----------+
  5. | n1 | 10 | 2 |
  6. | n1 | 15 | 1 |
  7. | n2 | 15 | 1 |
  8. +------+-----+----------+
  9. 3 rows in set (0.01 sec)

        简单东西, 不多说。  可以把select name, count(*) from t1 group by name; 固定下来, 作为一个基本的“范式”应用。



        



相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载