MySQL:如何统计一条记录的匹配条件,根据它进行选择和排序

MySQL:如何统计一条记录的匹配条件,根据它进行选择和排序,mysql,Mysql,要选择post ID并根据where语句中匹配条件的数量对其进行排序,我将使用以下非特定的WordPress查询: SELECT DISTINCT p.ID, -- @matches -- Not to be selected in the final query FROM (SELECT @matches := 0) dummy_table, -- Declare user var within a single query wp_posts p INNER JOIN wp_ter

要选择post ID并根据where语句中匹配条件的数量对其进行排序,我将使用以下非特定的WordPress查询:

SELECT DISTINCT p.ID,
  -- @matches -- Not to be selected in the final query
FROM
  (SELECT @matches := 0) dummy_table, -- Declare user var within a single query
  wp_posts p
INNER JOIN wp_term_relationships tr ON (p.ID = tr.object_id)
INNER JOIN wp_term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
INNER JOIN wp_terms t ON (t.term_id = tt.term_id)
WHERE 1 = 1
  AND ( @matches := 0 ) IS NOT NULL -- Reset counting var. Returns true for this condition
  AND (
       -- START comparing and counting matches
       ( tt.taxonomy = 'tags'
         AND t.term_id IN (110, 84) -- Post has a matching tag
         AND (@matches := @matches + 1) -- Increment counter. Returns false
       )
       OR 
       ( tt.taxonomy = 'other-taxonomy'
         AND t.term_id IN (333, 330, 331) -- Post has a matching 'other-taxonomy' term
         AND (@matches := @matches + 1) -- Increment counter. Returns false
       )
       -- OR [... more of the same ...]
       -- END comparing and counting matches
       OR 1 = 1 -- Always return true for this OR-condition
      )
  AND ( 0 < @matches ) -- Only select with matches
ORDER BY 
  @matches DESC, RAND();" -- Order with match priority, then randomly
想法是这样的:我想选择所有符合我定义的分类术语之一的帖子,因此选择OR条件。但是因为我想根据匹配的数量来排序帖子,所以我需要计算所有匹配的条件,并强制OR条件检查每个匹配评估。每匹配变量计算假定AND条件无效,从而强制OR条件进一步迭代。 最后,计数器用于在找到任何匹配项时选择帖子,并根据匹配项的数量对帖子进行排序

然而,查询结果为0个选择,尽管my DB中确实存在具有匹配项的帖子。变量使用和计算按照进行设置。当我删除OR 1=1时,会找到POST,但计数器似乎没有重置匹配项为2,4,6,8

问题是:我如何解决这种情况?如何在单个查询中有效地计算帖子的匹配条件,并根据它们进行选择和排序