mysql 查询小技巧
数据字段中存放的是id集,形如 1,2,15,35 也可类推json格式
查询时不用拆分了, 用上 instr、concat搜索和连接字符串
查询fids中包含15的
select * from table where instr(concat(',', fids, ','), ',15,') > 0
查询时,多个字段 like 同个值
select * from table where concat(name, title) like '%哈哈%';
like多个值 and和的关系
like多个值 or的关系 可用regexp
select * from user where name regexp '四|五'
使用group by 时,数据出现不符合条件的取值,可通过 having 条件或 select max() 来筛选
使用别名排序,例如 大于当前时间升序,小于降序
select *,(if(unix_timestamp() > etime,1,0) as time) from table order by time asc,etime asc
查询的结果为:按时间升序,过期的在最后
查询时,多次左联同个表,影响效率
改为 加上条件单表搜索
查询时,左联on使用concat a left join b on a.tel=concat(b.k100,b.tel) 查询较慢
改为拆分条件左联 left(a.tel,4)=b.k100 and substring(a.tel,5)=b.tel b表建立联合索引 k100,tel
字段有null值时,null不和数字作比较
条件字段有null时,where b.id > 0 (能筛选出b表 不含null的记录)
where b.id < 0 (错误,不能筛选出b表 含null的记录) 应为 where b.id is null