select *,FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i%s') as date from user where FROM_UNIXTIME(create_time,'%Y-%m-%d %H:%i%s') > curdate() group by date order by date desc;
上面的sql语句,把create_time字段格式化为日期,而且按格式话后的字段查找和排序。mysql
细看可能会发现,group和order我都直接使用了格式化后的别名dete,而where查询则从新格式化了字段,这跟mysql的执行顺序有关。执行到where时,结果还没被查询出来,别名天然没法生效,须要注意下。web
select IFNULL(score1,score2) from score;
若是score1是NUll,则返回score2;不然返回score1sql
select IF(sex,'男','女') from user;
第一个参数是条件。若为浮点数,认为是0,返回‘女’svg
第一个参数也能够写成比较式:sex=1函数
select count(case when age>10 then id end) from user;
上面sql语句查询年龄大于10的用户数量ui
把数据表中的数据按中文字段值得拼音首字母排序,假设该字段为name编码
若是name的字符编码是latin_swedish_cicode
select * from user order by birary(name) asc;
若是name的字符编码是utf8_general_ciorm
select * form user where 1 order by convert(name using gbk) collate gbk_chinese_ci asc;
select * form user where id in(1,2,3,4,5) order by field(id,5,4,3,2,1);
返回的值会根据id 5,4,3,2,1排序xml
select concat(id,name,'666') from user;
concat()中的参数,可使字符串,也能够是数据表中的字段。当参数中的字段有一个为NULL时,则给行数据就为NULL了。若想避免这种状况,可使用CONCAT_WS(),用法略有不一样
alter table 表名 auto_increment=1;
使用group把指定字段相同的行合为一行后,除了group字段是咱们预期的值,行里其余字段可能不是咱们想要的。
好比说我想要合并后,时间字段create_time的值是最大的那个,但不少时候咱们不肯定这个create_time是最大仍是最小,这时候咱们须要本身在select 时增长本身想要的字段,好比:
select *,count(id),MAX(create_time) as last_time from pay_list group by uid;
① mysql执行查询语句时,关于为where条件的执行顺序,看网上不少说是从左到右顺序执行的,所以在查询数据量较大的表时,最好把能排除最多无效数据的条件放在最左(就算不对,也没啥损失)。
② 关于mysql in 条件的运行原理
select * from a where id in(id_str);
该语句的执行顺序相似于如下过程。
$a = select * from a; $b = id_str; $result = []; foreach($a as $v){ foreach($b as $vv){ if($v['id'] == $vv){ $resulr[] = $v; } } }
当where 须要多个in条件,且条件之间有关联时
好比咱们想筛选:北京,年龄在21,22 ;上海,年龄在22,23的人员
传统的写法:select * from A where address in (‘北京’,‘上海’) and age in (21,22,23); 是不对的,会筛选出:上海,年龄21 的无效数据
咱们能够把上面语句改成:select * from A where (address ,age) in ((‘北京’,‘21’),(‘北京’,‘22’),(‘上海’,‘22’),(‘上海’,‘23’),);