0

我有 3 个表,我想在其中检索与所有搜索条件匹配的帖子。标准是可能具有一个或多个值的分类法。例如,查找分类法“mediums”与“acrylic”和“oil”匹配的帖子

这是我想做的一个示例查询,但它显然不起作用:

SELECT DISTINCT p.* FROM wp_posts p 
LEFT JOIN wp_term_relationships txrm ON p.ID = txrm.object_id 
LEFT JOIN wp_term_taxonomy txm ON txrm.term_taxonomy_id = txm.term_taxonomy_id 
LEFT JOIN wp_terms trm ON txm.term_id = trm.term_id 
WHERE txm.taxonomy= 'mediums' AND ( trm.name LIKE '%Acrylic%' AND trm.name LIKE '%Oil%' ) 
AND p.post_status = 'publish' 
AND p.post_type = 'gallery'
GROUP BY p.ID 
ORDER BY p.post_date DESC

我该如何进行这项工作?

谢谢

4

1 回答 1

0

以防万一有人在寻找类似的东西,这就是我所采用的方法,非常有效,但我不确定它的效率如何:

SELECT DISTINCT p.* FROM wp_posts p
INNER JOIN (
    SELECT txrm.object_id
    FROM wp_term_relationships txrm
    LEFT JOIN wp_term_taxonomy txm ON txrm.term_taxonomy_id = txm.term_taxonomy_id
    LEFT JOIN wp_terms trm ON txm.term_id = trm.term_id
    WHERE txm.taxonomy = 'mediums'
    AND ( trm.name LIKE '%Acrylic%' OR trm.name LIKE '%Oil%' )
    GROUP BY txrm.object_id
    HAVING count(trm.name) = 2
    ) AS trm ON p.ID = trm.object_id
WHERE p.post_status = 'publish'
AND p.post_type = 'gallery'
GROUP BY p.ID
ORDER BY p.post_date DESC

所以子查询返回一个计数为 2 的 post_ids/object_ids 列表:

object_id|term.name
1        |oil
1        |acrylic
2        |oil

所以在上面,只有帖子 1 的计数为 2,因为它与油和丙烯酸相匹配。

于 2013-04-30T17:19:10.870 回答