How to select data from a key value pair table

只谈情不闲聊 提交于 2019-12-12 18:03:43

问题


Table A

id,parentID, key, value
1, 2, name, name1
2, 2, age, 20
3, 2, place, place1

50, 7, name, namex
51, 7, age, 20
52, 7, place, place1
........
101, 5, name, namez
102, 5, age, 23
103, 5, place, place2

I need to get all the date having plave = place1 and age = 20 in the bellow format

parentid, name, age, place
2, name1, 20, place1
7, namex, 20, place1

How to write the Mysql SQL query please help me


回答1:


You can use conditional aggregation to get all the info for a parentid on to one row and then use a where clause for the required condition.

select * from (
select parentid
,max(case when key='name' then value end) as name
,max(case when key='age' then value end) as age
,max(case when key='place' then value end) as place
from tableA
group by parentid 
) t
where place='place1' and age=20

This assumes there is only one row per key per parentid in the table.




回答2:


You need to join the table three times - once for the name, once for the age and last for the place. This will de-normalize your table, and then it's simple query to filter the criteria you want:

SELECT a.parentId, a.name, b.age, c.place from 
myTable as a inner join myTable as b on a.parentId = b.parentId
inner join myTable as c on a.parentId = c.parentId
where a.id = 1 and b.id = 2 and c.id = 3 
and b.age = 20 and c.place = 'place1';



回答3:


In the SELECT clause, you especify the column names you want in the result, in the FROM clause, you especify the tables where you are going to apply the query to, and in the WHERE clause you especify the conditions each row must meet in order to be on the result:

SELECT parentid, name, age, place 
FROM tableA
WHERE place="place1" AND age=20

You can check this link for more information.




回答4:


You need to use a lot of sub-query like this

SELECT 
    parentId,
    (SELECT aName.value FROM TableA aName WHERE aName.parentId = a1.parnetId and aName.KEY = 'name') as name,
    value as age,
    (SELECT aPlace.value FROM TableA aPlace WHERE aPlace.parentId = a1.parnetId and aPlace.KEY = 'place') as place
FROM TableA a1
WHERE 
    key = 'age' 
    AND 
    value = '20'
    AND 
        EXISTS (SELECT NULL FROM TableA a2 
            WHERE 
                a1.parentId = a2.parentId 
                AND
                a2.key = 'place'
                AND
                a2.value = 'place1')


来源:https://stackoverflow.com/questions/45111954/how-to-select-data-from-a-key-value-pair-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!