Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with SQL Query

Say I have 2 tables:

Person

 - Id
 - Name

PersonAttribute

 - Id
 - PersonId
 - Name
 - Value

Further, let's say that each person had 2 attributes (say, gender and age). A sample record would be like this:

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'

Question: how do I query this such that I get a result like this:

'John Doe', 'Male', '30'

like image 607
StackOverflowNewbie Avatar asked Jul 11 '26 23:07

StackOverflowNewbie


2 Answers

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'
like image 112
Amarghosh Avatar answered Jul 14 '26 14:07

Amarghosh


I think you need redesign your schema. Why not?

Person

 - Id
 - Name
 - Gender
 - Birthday
...
like image 21
msi77 Avatar answered Jul 14 '26 13:07

msi77



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!