我正在使用mysql中的sql查询,例如我正在插入像键和值对
这样的记录学生表
StdId StuName phnNum
1 John 87678
我正在student_metadata表中存储有关该学生的详细信息
S.NO FieldName FieldValue indexVal
1 college St.Anns 1
2 Address Arizona 1
3 IdNum 321 1
现在我想获取student_metadata
SELECT
student.stdId AS StdId
fieldValue AS fieldValue
FROM
Student
LEFT JOIN
Student_metadata ON Student.StdId = student_metadata.indexVal
Where
Student_metadata.fieldName IN ('College','IdNum')
我的问题是,如果我使用' IN'它给了我2行。如下所示
StudentId fieldValue
1 St.Anns
1 321
我想获取如下所示
StudentId fieldValue IdNum
1 St.Anns 321
任何人都可以在此建议我
答案 0 :(得分:3)
您可以使用条件聚合来进行透视:
select
s.stdid,
max(case when m.fieldname = 'College' then fieldvalue end) as fieldvalue,
max(case when m.fieldname = 'IdNum' then fieldvalue end) as idnum
from student s
left join student_metadata m on s.stdid = m.indexval
where m.fieldname in ('College','IdNum')
group by s.stdid
答案 1 :(得分:0)
您可以使用数据透视表样式查询:
SELECT
a.`StuName`,
COALESCE(b.`FieldVal`) as `college`,
COALESCE(c.`FieldVal`) as `IdNum`
FROM `Student` a
LEFT JOIN `student_metadata` b
ON b.`indexVal` = a.`StdId` AND b.`FieldName` = 'college'
LEFT JOIN `student_metadata` c
ON c.`indexVal` = a.`StdId` AND c.`FieldName` = 'IdNum'
WHERE a.`StdId` = 1
GROUP BY a.`StdId`