SQL查询:如何正确分组项目?

时间:2013-05-14 09:54:34

标签: mysql sql wordpress

你能帮忙修改下面的SQL查询,以便它可以在mySQL中运行吗?目前,错误消息是表t1不存在。我想得到一个包含“post_title”,“name1”,“url1”列的表格。

如果有帮助,则可以在Wordpress CMS数据库上测试此查询

SELECT t1.post_title,
       (select meta_value from t1 where t1.meta_key='name1_class' limit 1) as name1,
       (select meta_value from t1 where t1.meta_key='url1_class' limit 1) as url1
  FROM (select pm.post_id as id, pm.meta_key, pm.meta_value, p.post_title, t.slug from wp_2_postmeta pm
    inner join wp_2_posts p on pm.post_id = p.id
    inner join wp_2_term_relationships tr on tr.object_id = p.id    
    inner join wp_2_term_taxonomy tt on tr.term_taxonomy_id = tt.term_taxonomy_id
    inner join wp_2_terms t on t.term_id = tt.term_id
    where post_type='footercolumn' and post_status='publish' and pm.meta_key like '%class') t1 

“FROM”子句中t1表的子查询生成如下数据集:

'id', 'meta_key',  'meta_value', 'post_title', 'slug' 
'18', 'name1_class', 'Our Work', 'Who we are', 'column1' 
'18', 'url1_class', '/work.html', 'Who we are', 'column1' 
'18', 'name1_class', 'Our Team', 'About', 'column2' 
'18', 'url1_class', 'team.html', 'About', 'column2

我希望结果表为:

'title',      'name1',     'url1'
'Who we are', 'Our Work',  'work.html'
'About',      'Our Team',  'team.html'

感谢

2 个答案:

答案 0 :(得分:0)

看起来你正在尝试使用子选择来模拟CTE(公用表表达式),但我无法想到一种方法来使其工作。

好消息是,如果您可以使用聚合来查找数据,则不需要子选择。

SELECT t1.post_title,
       MAX(CASE WHEN meta_key='name1_class' THEN meta_value END) as name1,
       MAX(CASE WHEN meta_key='url1_class' THEN meta_value END) as url1
  FROM (select pm.post_id as id, pm.meta_key, pm.meta_value, p.post_title, t.slug 
        from wp_2_postmeta pm
        inner join wp_2_posts p on pm.post_id = p.id
        inner join wp_2_term_relationships tr on tr.object_id = p.id    
        inner join wp_2_term_taxonomy tt 
           on tr.term_taxonomy_id = tt.term_taxonomy_id
        inner join wp_2_terms t on t.term_id = tt.term_id
        where post_type='footercolumn' and post_status='publish' and pm.meta_key 
              like '%class') t1 

答案 1 :(得分:0)

我甚至认为你不需要子查询,你可以重新加入postmeta表两次以获取列并简化查询:

SELECT       p.post_title
            ,pma.meta_value AS name1
            ,pmb.meta_value AS url1

FROM        wp_2_posts p

JOIN        wp_2_postmeta pma
ON          p.ID = pma.post_id
AND         pma.meta_key = 'name1_class'

JOIN        wp_2_postmeta pmb
ON          p.ID = pmb.post_id
AND         pmb.meta_key = 'url1_class'

JOIN        wp_2_term_relationships tr
ON          tr.object_id = p.id 

JOIN        wp_2_term_taxonomy tt 
ON          tr.term_taxonomy_id = tt.term_taxonomy_id

JOIN        wp_2_terms t 
ON          t.term_id = tt.term_id

WHERE       p.post_type='footercolumn'
AND         p.post_status='publish'

如果出于某种原因,每个帖子有多个name1_classurl1_class值会产生重复的post_title行,请添加GROUP BY以消除此行。

GROUP BY    post_title

如果您因NULLname1_class中的url1_class错过了值,则可以通过将pma / pmb上的JOIN更改为LEFT OUTER JOIN来更正该值。 INNER JOIN是默认的连接类型,因此在这种情况下无需指定INNER