0

您能否帮助修改以下 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'

谢谢

4

2 回答 2

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 
于 2013-05-14T10:05:54.730 回答
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

如果您由于NULLin丢失了值,name1_class或者url1_class您可以通过将 pma/pmb 上的 JOIN 更改为LEFT OUTER JOIN. 是默认的连接类型,所以在这种情况下INNER JOIN不需要指定INNER

于 2013-05-14T10:36:08.583 回答