thinkphp是国内非常流行的一个PHP语言开发框架,但是在项目开发中随着数据量的不断增大,数据库已经成为影响平台发展的瓶颈问题之一,所以本文波波将简单分享thinkphp5下数据库的水平分表,以及分表后对数据的增删改查。以提升整体性能。
一、数据库分表:
1、我们首先创建数据表system_history。
CREATE TABLE `system_history` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`member_id` int(10) NOT NULL DEFAULT '0',
`history` int(10) DEFAULT NULL,
`sex` smallint(1) DEFAULT NULL,
`age` smallint(3) DEFAULT NULL,
`type` smallint(1) DEFAULT NULL,
`datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`is_deleted` smallint(1) DEFAULT '0' COMMENT '1已删0正常',
PRIMARY KEY (`id`,`member_id`),
KEY `member_id` (`member_id`),
KEY `age` (`age`),
KEY `sex` (`sex`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY LINEAR KEY (member_id)
PARTITIONS 4 */
2、手动添加数据表system_history_1,system_history_2,system_history_3,system_history_4字段与数据类型与system_history保持一致。
二、数据库增删改查:
1、插入数据。
$rule = array('type' => 'LINEAR KEY','num' =>4);
$temparr = array('member_id'=>$uid);
$time = time();
Db::name("SystemHistory")->partition($temparr,'member_id',$rule)
->insert(array('member_id'=>$uid,'history'=>$view_id,'type'=>$type,'datetime'=>date("Y-m-d H:i:s",$time)));
2、查询数据。
$rule = array('type' => 'LINEAR KEY','num' =>4);
$temparr = array('member_id'=>$uid);
$time = time();
$arr = Db::name("SystemHistory")->partition($temparr,"member_id",$rule)
->where(array('member_id'=>$uid,'history'=>$view_id,'type'=>$type))
->whereTime('datetime','today')->find();
3、修改数据。
$rule = array('type' => 'LINEAR KEY','num' =>4);
$temparr = array('member_id'=>$uid);
$time = time();
Db::name("SystemHistory")->partition($temparr,'member_id',$rule)
->where(array('member_id'=>$uid,'history'=>$view_id,'type'=>$type))
->whereTime('datetime','today')->update(array('datetime'=>date("Y-m-d H:i:s",$time),'is_deleted'=>0));
4、删除数据。
删除数据与查询数据雷同,方法修改为delete()即可。
关于数据库水平分表,其实不止这一种方法。但是不管用哪种方法,其用法都是大同小异,故本文内容仅用于参考。不作为实际项目开发中的应用。