【194】PostgreSQL 14.5 编写SQL从身份证号中查找性别,并且更新性别字段。

假设有一张用户表 t_user ,该表设计如下:

id:  character varying      主键
name: character varying     姓名
idcard: character varying   身份证号
gender: smallint            性别,女是0,男是1

根据身份证号查找所有未填写性别字段的女性SQL:

select * from t_user where char_length(idcard)=18 
and gender is null 
and substring(idcard, 17, 1) in ('0','2','4','6','8');

根据身份证号查找所有未填写性别字段的男性SQL:

select * from t_user 
where char_length(idcard)=18 and gender is null 
and substring(idcard, 17, 1) in ('1','3','5','7','9');

根据身份证号更新性别字段,其中第一句是更新女性的,第二句是更新男性的。

update t_user set gender=0 
where char_length(idcard)=18 and gender is null 
and substring(idcard, 17, 1) in ('0','2','4','6','8');

update t_user set gender=1  
where char_length(idcard)=18 and gender is null 
and substring(idcard, 17, 1) in ('1','3','5','7','9');

你可能感兴趣的:(数据库,postgresql,sql,数据库)