如何从键值对表中选择数据

时间:2017-07-14 21:40:04

标签: mysql sql entity-attribute-value

表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

我需要以波纹管格式

获得plave = place1和age = 20的所有日期
parentid, name, age, place
2, name1, 20, place1
7, namex, 20, place1

如何编写Mysql SQL查询请帮帮我

4 个答案:

答案 0 :(得分:6)

您可以使用条件聚合将parentid的所有信息放到一行,然后使用where子句获取所需条件。

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

这假设表中每个密钥只有一行。

答案 1 :(得分:1)

你需要加入桌子三次 - 一次是名字,一次是年龄,最后一次是这个地方。这将对您的表进行反规范化,然后通过简单的查询来过滤您想要的标准:

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';

答案 2 :(得分:0)

在SELECT子句中,您可以在结果中指定所需的列名,在FROM子句中,您可以指定要将查询应用于的表,并在WHERE子句中指定每行必须满足的条件见面是为了得到结果:

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

您可以查看this link了解详情。

答案 3 :(得分:0)

你需要使用很多这样的子查询

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')