sql实现有数据就更新,没有就插入
首先建表:
create table lxt_user3(
user_id int unsigned not null primary key auto_increment comment '用户id',
qq_open_id varchar(32) unique,---------------》该表中得有一个字段为unique,否则执行下面的sql语句时会达不到预期的效果
role_id int unsigned not null,
category_id int unsigned,
status int unsigned,
name varchar(20) default '',
img varchar(100) default '',
password varchar(32) default '',
salt varchar(4) default '',
sex int,
email varchar(30) default '',
telephone varchar(20) default '',
address varchar(100) default '',
navigation varchar(1000) default '',
simple_menu varchar(1000) default '',
dashboard text,
reg_ip varchar(15) default '',
reg_time int unsigned default 0,
last_login_time int unsigned default 0,
lostpw_time int unsigned default 0,
weixinid int,
last_read_time varchar(500) default '',
qqnumber int,
realname varchar(30) default '',
Position varchar(20) default ''
)engine=MyISAM default charset=utf8 comment '用户表';
关键的一条sql语句:
$sql="INSERT INTO lxt_user3 SET realname='$realname',role_id='$role_id',sex='$sex',name='$name',qq_open_id='$qq_open_id' ON DUPLICATE KEY UPDATE realname='$realname',role_id='$role_id',sex='$sex',name='$name',qq_open_id='$qq_open_id'";
问题二:
那么批量的数据能否解决呢?可以得,如下:
$new_insert_str=rtrim($insert_str,',');//$new_insert_str是已经拼接好的字符串,类似(),(),()
M()->execute("insert into table (id,hos_id,project_name,contract_date,check_date,service_time,end_date,remark,zz_id,is_del,project_type) values $new_insert_str ON DUPLICATE KEY UPDATE hos_id=values (hos_id),project_name=values (project_name),contract_date=values (contract_date),check_date=values (check_date),service_time=values (service_time),end_date=values (end_date),remark=values (remark),zz_id=values (zz_id),is_del=values (is_del),project_type=values (project_type)");