博客是我工作的好帮手,遇到困难就来博客找资料
分类: 系统运维
2015-06-25 15:17:49
CREATE TABLE `student` (
1.测试一
select * from student;
a
a
c
用distinct过滤掉两列都相同的记录
select distinct name,age from student;
返回
a
c
2.测试二
将表student的数据改为如下:
select * from student;
c
c
select distinct name,age from student;
返回如下,说明distinct后面有多于一列的字段时,只有每列的值完全相同才过滤
c
c
3.测试三
select * from student;
name age height
c
c
b
group by按两列同时分组
select name,age,sum(height) from student group by name,age;
b
c
group by按两列同时分组,同时在后面加上having的条件
select name,age,sum(height) as n from student group by name,age having n > 500;
返回
c
4.测试四
关于group by后面limit的测试
select songname,sengerid,count(sengerid) as n from t_song
group by songname,sengerid having n > 1 ORDER BY n DESC,songid ASC limit 10;
未知
共同渡过
风继续吹
倩女幽魂
无心睡眠
罗百吉超嗨派对连续组曲
拒绝再玩
风再起时
每天爱你多一些
千言万语
select songname,sengerid,count(sengerid) as n from t_song
group by songname,sengerid having n > 1 ORDER BY n DESC,songid ASC limit 5;
未知
共同渡过
风继续吹
倩女幽魂
无心睡眠
经过以上两个测试可以看出,如果sql语句中含有limit,limit是对用group by进行分组,并进行相关计算以后的limit操作,而不是对limit后面的指定记录数进行分组,从n那一列的数据每一行的值都大于10就可以看出来。
5.测试五
用以下的两种形式的distinct均可以得到相同的记录数,写法不一样,结果是一样的。
select count(distinct(songid)) from feedback;
select count(distinct songid) from feedback;
6.测试六
field singername is string,max(singername),如果singername有些列为空,有些列不为空,则max(singername)取非空的值,如果一列为zxx,一列为lady,则取zxx,按字母顺利取的。
select feedback_id,songid,songname,max(singername),max(time) as new_time from feedback group by songid order by new_time desc;
7.Sql语句中where,group by,order by及limit的顺序
where xxx,group by xxx,order by xxx,limit xxx
8.关于group by与count的问题
如果sql语句中含有group by,则最好不要将count sql转换为select count(*) from xxx,否则select与from之间的字段很有可能是后面要使用的,例如
select feedback_id,songid,songname,max(singername),max(time) as new_time from feedback group by songid order by new_time desc;
MySQL Query Error: SELECT COUNT(*) FROM feedback GROUP BY songid ORDER BY new_time DESC Error Info:Unknown column 'new_time' in 'order clause'