表 A 有两列 属性 user,like
一个user可能有多喜好(like)。即表中有很多user,每个user可能出现多次,每次对应一个like。
sql语句查询,所有的user,以及user出现的次数。
试了好几个,终于试对了 用 group by(
group by 有一个原则,就是 select 后面的所有列中,没有使用聚合函数的列,必须出现在 group by 后面
)
mysql> select user,count(user) from A group by user;+------+-------------+| user | count(user) |+------+-------------+| a | 3 | | b | 2 | | c | 4 | +------+-------------+3 rows in set (0.01 sec) 等同于 mysql> select user,count(*) from A group by user;
之前 用过几个:
1mysql> select distinct(user),count(*) from A ;+------+----------+| user | count(*) |+------+----------+| a | 9 | +------+----------+1 row in set (0.00 sec)2mysql> select distinct(user),count(user) from A ;+------+-------------+| user | count(user) |+------+-------------+| a | 9 | +------+-------------+1 row in set (0.00 sec)3mysql> select count(user) from A where user in (select distinct(user) from A) ;+-------------+| count(user) |+-------------+| 9 | +-------------+1 row in set (0.00 sec)这三个,在我出来正确答案后觉得错的离谱,第三个结果可以理解,但是前两个结果,我无法理解,不过自己写着也觉得没什么逻辑,如果有哪位大神看到,希望能教教我~