2

我希望找到具有两种不同标准的产品。

我首先用来搜索一个条件的代码是;

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;

这将返回所有具有“pa_1_scale”属性和 ts.term_id = 400的产品 (Object_ID) 。我也可以使用不同的WHERE语句返回所有带有product_cat 和 ts.term_id = 397的产品

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

UNION ALL 只是结合了两者。如何让 SQL 选择这两个条件?我知道结合这两个条件的 WHERE 语句将不起作用,因为我认为没有表行包含这两个值?

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

4

1 回答 1

1

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

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 中使用该类WPDB及其方法在 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>';

它应该工作。

于 2020-10-12T20:42:23.270 回答