将键/值元数据作为列添加到SQL查询中

时间:2016-02-13 16:18:04

标签: mysql sql

我做了一个SQL查询,它将内容和元数据作为列

返回
SELECT 
    content.content_id AS id,
    content.content_title AS author,
    content.content_body AS review,
    content.content_date as date,
    m0.meta_value AS email,
    m1.meta_value AS origin,
    m2.meta_value AS recommend,
    m3.meta_value AS avatar
FROM
    molly_contents content,
    molly_content_meta m0,
    molly_content_meta m1,
    molly_content_meta m2,
    molly_content_meta m3
WHERE
    content.content_type = 'review'
        AND content.content_id = m0.meta_content_id
        AND m0.meta_name = 'email'
        AND content.content_id = m1.meta_content_id
        AND m1.meta_name = 'origin'
        AND content.content_id = m2.meta_content_id
        AND m2.meta_name = 'recommendation'
        AND content.content_id = m3.meta_content_id
        AND m3.meta_name = 'avatar'
ORDER BY
    content.content_date DESC

问题是,如果缺少元数据,它将不会返回该记录。 是否有任何解决方案将每个记录作为单个行返回,并将元名称作为列名称,如果没有元名称,则将其留空?

1 个答案:

答案 0 :(得分:1)

我认为这比条件聚合更简单:

SELECT c.*,
       MAX(CASE WHEN m.meta_name = 'email' THEN m.metavalue END) as email,
       MAX(CASE WHEN m.meta_name = 'origin' THEN m.metavalue END) as email,
       MAX(CASE WHEN m.meta_name = 'recommendation' THEN m.metavalue END) as recommendation,
       MAX(CASE WHEN m.meta_name = 'avatar' THEN m.metavalue END) as avatar
FROM molly_contents c left join
     molly_content_meta m
     ON c.content_id = m.meta_content_id
GROUP BY c.content_id;

您的查询的根本缺陷是您在from子句中使用逗号。这是一个简单的规则:从不FROM子句中使用逗号;始终使用显式JOIN语法。然后,您就可以将联接更改为LEFT JOIN,这是解决问题的另一种方法。