简体   繁体   English

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

[英]How to select data from a key value pair table

Table A 表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 我需要以波纹管格式获得plave = place1和age = 20的所有日期

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

How to write the Mysql SQL query please help me 如何编写Mysql SQL查询请帮帮我

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. 您可以使用条件聚合将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

This assumes there is only one row per key per parentid in the table. 这假设表中每个parentid只有一个键。

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

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子句中,您可以在结果中指定所需的列名,在FROM子句中,您可以指定要将查询应用于的表,在WHERE子句中,您可以指定每行必须满足的条件结果如下:

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

You can check this link for more information. 您可以查看此链接以获取更多信息。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM