在一次开发时候想把一条sql把人员的基本信息和其他属性全部查出来,但是其他属性查出来是一个list,所以使用用行转列来解决
查出来的基本属性如下图
SELECT
hi.ctyName,
hi.builderName,
hi.unitName,
hi.NAME AS houseName,
p.NAME,
p.mobile,
p.id,
p.idNbr,
p.householdPace,
p.householdPaceDetail,
n.NAME AS nation
FROM
person_info pi
LEFT JOIN house_info hi ON pi.houseId = hi.id
LEFT JOIN person p ON pi.personId = p.id
LEFT JOIN nation n ON n.CODE = p.nation
WHERE
pi.STATUS = 1
AND (
YEAR (
NOW())- SUBSTRING( p.idNbr, 7, 4 )) >= 5
AND (
YEAR (
NOW())- SUBSTRING( p.idNbr, 7, 4 )) <= 50
ORDER BY
hi.id
其他属性
SELECT * from person_attr_val where personId = 126179
然后想把这个两个sql合并成一个,但是一个是一条数据,一个结果是个list,所以用mysql中的行转列解决
SELECT
hi.ctyName,
hi.builderName as buildName ,
hi.unitName,
hi.NAME AS houseName,
pt.name as personType,
p.name,
p.mobile,
p.id,
p.idNbr,
p.householdPace,
p.householdPaceDetail,
n.name AS nation,
IF(INSTR(p.tag,'26') >0 ,'是','否') as tag,
pa.*
FROM
person_info pi
LEFT JOIN house_info hi ON pi.houseId = hi.id
LEFT JOIN person p ON pi.personId = p.id
LEFT JOIN nation n ON n.CODE = p.nation
LEFT JOIN person_type pt ON pt.code = pi.registrationType
LEFT JOIN ((SELECT personId ,
Max(case WHEN attrId = '32' THEN `value` ELSE NULL END) as "学历",
Max(case WHEN attrId = '13' THEN `value` ELSE NULL END) as "政治面貌",
Max(case WHEN attrId = '42' THEN `value` ELSE NULL END) as "从事职业",
Max(case WHEN attrId = '43' THEN `value` ELSE NULL END) as "从事单位"
from person_attr_val GROUP BY personId) as pa) on pa.personId=pi.personId
WHERE
pi.status = 1
现在完美解决了,但是又遇到另一个问题,就是我们有一个人员标签字段,可以有多个属性用“,”来分割开,我要判断每个人是否存在这个属性,开始我用CONTAINS这个函数,但是报 Invalid GIS data provided to function mbrcontains错误,结果是InnoDB不支持这个函数,后来去mysql官方查询发现了INSTR函数可以判断,就是这条IF(INSTR(p.tag,'26') >0 ,'是','否') as tag,当存在时,就会返回匹配到的位置,此时所以问题全部解决