mysql位运算
在设计数据表时,常用一个int字段bit的每一位代表不同的意义,如php的错误级别。举个例子,如果需要bit代表1,2,3,4,5,那么可以用1、2、4、8、16代替,分别将字段的不同二进制位设为1即可。这就是mysql的位运算的功能。
1. 查询bit等于3的所有记录
使用与运算&
select * from table where bit & 8 = 8;
2. 将2赋值给bit
使用或运算|
update table set bit = bit | 2;
3. 从bit中删除2
使用异或运算^
update table set bit = bit^2;
修改表结构
1. 增加字段
alter table 表名 add column 字段名 类型 [属性(not null、default) comment ‘描述’ first/after 字段
2. 修改字段
修改字段类型
alter table ‘表名’ modify 字段 类型 [属性]
修改字段名称
alter table ‘表名’ change 旧字段 新字段 类型 [属性]
3.删除字段
alter table drop 字段
count与if联合使用
现有一张表test,数据如下
id status
1 2
2 1
count使用
需要查询test表中数据总量
select count(1) from test
count与if联合
查询表中status大于1的记录总量
select count(if(status>1,1,null)) as num from test
查询表中status大于1并且id大于1的记录总量
select count(if(status>1 and id >1,1,null)) as num from test
日期字符串与时间戳转换
时间戳–>字符串 from_unixtime
例:select id, from_unixtime(create_time) from table1;
字符串–>时间戳 unix_timestamp
例:select unix_timestamp(“2016-08-11 20:45:00 “) ;