如何从存储键/值的表中检索数据作为常规表?

时间:2016-07-07 18:44:28

标签: mysql

我有一个具有这种结构的元表:

--------------------------------------
| id | res_id | meta_key | meta_value|
-----+--------+----------+------------
| 1  |  5     |name      | test1     |
-----+--------+----------+------------
| 2  |  5     |family    | test2     |
-----+--------+----------+------------
| 3  |  5     | title    | test      |
--------------------------------------

和资源表:

-----------------------------
| id | indate   | cost      |
-----+----------+-----------+
| 5  | 14448565 | 200000    |
-----------------------------

现在我想创建一个查询来获得这个结果:

-----+--------+--------+-------+------+-----------
| id | name   | family | title |cost  | indate   |
-----+--------+--------+--------------+-----------
| 5  |  test1 |test2   | test  |200000| 14448565 |
-----+--------+--------+--------------+-----------

有没有办法做这项工作?

2 个答案:

答案 0 :(得分:1)

您可以在元

上使用内部联接
select  b.meta_value as name,  c.meta_value as family, d.meta_value as title, 
        a.cost, a.indate
from resource as a
inner join meta as b on a.id = b.res_id and b.meta_key = 'name'
inner join meta as c on a.id = c.res_id and c.meta_key = 'family'
inner join meta as d on a.id = d.res_id and d.meta_key = 'title';

答案 1 :(得分:0)

也是一种透视表的简单方法:

select
    r.id,
    p_meta.name,
    p_meta.family,
    p_meta.title,
    r.indate,
    r.cost
from (
    select
        res_id,
        max(case when meta_key = 'name' then meta_value end) as name,
        max(case when meta_key = 'family' then meta_value end) as family,
        max(case when meta_key = 'title' then meta_value end) as title
    from meta
    group by res_id ) p_meta
inner join resource r
on r.id = p_meta.res_id

SUB QUERY DEMO

或者只使用LEFT JOIN

select
    m.res_id as id,
    max(case when m.meta_key = 'name' then meta_value end) as name,
    max(case when m.meta_key = 'family' then meta_value end) as family,
    max(case when m.meta_key = 'title' then meta_value end) as title,
    r.indate,
    r.cost
from meta m
left join resource r
on m.res_id = r.id
group by m.res_id

LEFT JOIN DEMO

我更喜欢简单易懂的子查询。