对分类表的SQL查询连接没有返回我预期的结果

时间:2017-05-16 作者:Anthony

我想获得所有具有特定分类法术语a和特定分类法术语B的帖子。

以下是我正在运行的查询:

        SELECT wp_posts.ID, wp_posts.post_title 
        FROM wp_posts 
        INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id 
        INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id 
        INNER JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id 
        WHERE (wp_term_taxonomy.taxonomy = \'category\' AND wp_terms.slug in (\'uncategorized\'))
        AND (wp_term_taxonomy.taxonomy = \'post_tag\' AND wp_terms.slug in (\'red\'))
        ORDER BY ID DESC
尽管查询了具有“未分类”类别和“红色”标记的帖子的DB/WP安装,但仍返回0个结果

enter image description here

2 个回复
SO网友:Anthony

正如@Mark Kaplen提到的,WP API可以显示执行的查询

下面是一个简单的查询,使用模板中的API查看发生了什么:

<?php
/*
 * Template Name: Troubleshooting
 */

$args = array(
    \'post_type\' => \'post\',
    \'tax_query\' => array(
        \'relation\' => \'AND\',
        array(
            \'taxonomy\' => \'category\',
            \'field\'    => \'slug\',
            \'terms\'    => array( \'uncategorized\' ),
        ),
        array(
            \'taxonomy\' => \'post_tag\',
            \'field\'    => \'slug\',
            \'terms\'    => array( \'red\' ),
        ),
    ),
);
$query = new WP_Query( $args ); 
echo $query->request;

SO网友:Mosrur

您就快到了,但我只是稍微修改了SQL,觉得下面的解决方案应该可以做到这一点-

SELECT wp_posts.ID, wp_posts.post_title
FROM wp_posts
         INNER JOIN wp_term_relationships ON wp_posts.ID = wp_term_relationships.object_id
         INNER JOIN wp_term_taxonomy ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
         INNER JOIN wp_terms ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE wp_term_taxonomy.taxonomy IN (\'category\', \'post_tag\')
  AND wp_terms.slug in (\'uncategorized\', \'red\')
ORDER BY ID DESC;

结束