使用 SQL 在 Woocommerce 中获取具有特定属性术语和特定类别术语的产品

Get products with specific attribute term and specific category term in Woocommerce using SQL

我希望找到符合两个不同标准的产品。

我第一次用来搜索一个条件的代码是;

SELECT rel.object_id, rel.term_taxonomy_id, tt.taxonomy, tt.term_id, ts.name
FROM df1wrmw_term_taxonomy tt
INNER JOIN df1wrmw_term_relationships rel ON tt.term_taxonomy_id = rel.term_taxonomy_id
INNER JOIN df1wrmw_terms ts ON tt.term_id = ts.term_id
WHERE tt.taxonomy = "pa_1_scale"
AND ts.term_id = 400;

这 return 具有属性 "pa_1_scale" 和 ts.term_id = 400 的所有那些产品 (Object_ID) .我还可以对 return 所有具有 product_cat 和 ts.term_id = 397 的产品执行此操作,使用不同的 WHERE[=26] =] 声明

WHERE tt.taxonomy = "product_cat"
AND ts.term_id = 397

UNION ALL 只是将两者结合起来。我如何获得 SQL 到 select 这两个条件?我知道结合这两个条件的 WHERE 语句将不起作用,因为我认为没有 table 行包含这两个值?

任何可用的帮助都会很棒。

您可以尝试使用以下方法连接具有不同变量引用的重复表,从而将两个查询合并为一个查询:

SELECT tr.object_id, tr.term_taxonomy_id,  tt.taxonomy,  t.term_id,  t.name,
    tr2.term_taxonomy_id as term_taxonomy_id2, tt2.taxonomy as taxonomy2, 
    t2.term_id as term_id2, t2.name as name2
FROM df1wrmw_term_relationships tr
INNER JOIN df1wrmw_term_taxonomy tt
    ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN df1wrmw_terms t
    ON tt.term_id = t.term_id
INNER JOIN df1wrmw_term_relationships tr2
    ON tr.object_id = tr2.object_id
INNER JOIN df1wrmw_term_taxonomy tt2
    ON tr2.term_taxonomy_id = tt2.term_taxonomy_id
INNER JOIN df1wrmw_terms t2
    ON tt2.term_id = t2.term_id
WHERE tt.taxonomy = 'pa_1_scale'
    AND t.term_id = 400
    AND tt2.taxonomy = 'product_cat'
    AND t2.term_id = 397

或者您可以在 WordPress 中使用 class WPDB and its methods 在 PHP:

中获得 SQL 查询结果
global $wpdb;

$results = $wpdb->get_results("
    SELECT tr.object_id, tr.term_taxonomy_id,  tt.taxonomy,  t.term_id,  t.name,
        tr2.term_taxonomy_id as term_taxonomy_id2, tt2.taxonomy as taxonomy2, 
        t2.term_id as term_id2, t2.name as name2
    FROM {$wpdb->prefix}term_relationships tr
    INNER JOIN {$wpdb->prefix}term_taxonomy tt
        ON tr.term_taxonomy_id = tt.term_taxonomy_id
    INNER JOIN {$wpdb->prefix}terms t
        ON tt.term_id = t.term_id
    INNER JOIN {$wpdb->prefix}term_relationships tr2
        ON tr.object_id = tr2.object_id
    INNER JOIN {$wpdb->prefix}term_taxonomy tt2
        ON tr2.term_taxonomy_id = tt2.term_taxonomy_id
    INNER JOIN {$wpdb->prefix}terms t2
        ON tt2.term_id = t2.term_id
    WHERE tt.taxonomy = 'pa_1_scale'
        AND t.term_id = 400
        AND tt2.taxonomy = 'product_cat'
        AND t2.term_id = 397
");

// Display preformatted raw output
echo '<pre>' . print_pr($results, true) . '</pre>';

应该可以。