查询AND段塞值不起作用的位置

时间:2019-05-08 作者:Galloway Grumblefield

我意识到这不是最优雅的sql。我修改了此查询,其中原始查询仅从单个类别(slug 的字段terms 表)。我试图获得一个结果集,它返回具有多个类别(或段塞)的项作为属性。

这不会返回行,即使项目的类别列表中同时包含“arizona”和“speech language Pathogist”:

SELECT p.ID FROM wp_term_relationships tr 
JOIN wp_posts p ON tr.object_id = p.ID 
JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id 
JOIN wp_terms t ON tt.term_id = t.term_id 
WHERE p.post_parent = 220 AND t.slug = \'arizona\' AND t.slug = \'speech-language-pathology\' AND p.post_status = \'publish\'
但是,如果删除和条件之一,此查询将生成一个结果集:

SELECT p.ID FROM wp_term_relationships tr 
JOIN wp_posts p ON tr.object_id = p.ID 
JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id 
JOIN wp_terms t ON tt.term_id = t.term_id 
WHERE p.post_parent = 220 AND t.slug = \'arizona\' AND p.post_status = \'publish\'
我的SQL有点生疏,我看不出t.slug=\'something\'和t.slug=\'something-other\'是如何不合逻辑的。

1 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

您可以使用WP API这样做:

$args = [
    \'post_type\' => \'post\',
    \'tax_query\' => [
        \'relation\' => \'AND\',
        [
            \'taxonomy\' => \'your_taxonomy_name\',
            \'field\'    => \'slug\',
            \'terms\'    => array( \'arizona\', \'speech-language-pathology\' ),
        ]
    ],
];
$query = new WP_Query( $args );
然后您可以使用$query 就像任何标准的post循环一样。

如果您只需要ID,可以使用fields 选项WP_Query, 但请记住,您不会获得其他方式可能获得的所有缓存和性能好处,尤其是如果您要将ID传递到get_post

$args = [
    \'post_type\' => \'post\',
    \'tax_query\' => [
        \'relation\' => \'AND\',
        [
            \'taxonomy\' => \'your_taxonomy_name\',
            \'field\'    => \'slug\',
            \'terms\'    => array( \'arizona\', \'speech-language-pathology\' ),
        ]
    ],
    \'fields\' => \'ids\'
];
$query = new WP_Query( $args );
$posts = $query->get_posts(); // $posts is an array of post IDs

相关推荐

problem with sql query

我对quotes和query有问题。我的代码: $this->table_name= \'table_name\'; $how_much = $this->wpdb->get_var($this->wpdb->prepare(\"SELECT COUNT(*) FROM {$this->table_name}\")); 我没有任何通知或错误和网站故障。EDIT可能$wpdb->prepare 需要参数才能工作。