假设我有2张桌子:
Person
- Id
- Name
PersonAttribute
- Id
- PersonId
- Name
- Value
此外,假设每个人都有2个属性(例如,性别和年龄)。样本记录如下:
Person->Id = 1
Person->Name = 'John Doe'
PersonAttribute->Id = 1
PersonAttribute->PersonId = 1
PersonAttribute->Name = 'Gender'
PersonAttribute->Value = 'Male'
PersonAttribute->Id = 2
PersonAttribute->PersonId = 1
PersonAttribute->Name = 'Age'
PersonAttribute->Value = '30'
问题:如何查询此结果,这样的结果:
'John Doe','Male','30'
最佳答案
SELECT p.name, p1.Value, p2.Value
FROM Person p, PersonAttribute p1, PersonAttribute p2
WHERE p.Id = p1.PersonId AND p.Id = p2.PersonId
AND p1.Name = 'Gender' AND p2.Name = 'Age'