Wordpress查询添加INNER / LEFT JOIN。为什么或如何删除/阻止INNER / LEFT JOIN?

时间:2017-04-21 12:05:04

标签: php mysql wordpress join filter

我正在为wordpress中的帖子使用过滤器,它使用来自postsmeta的数据: 我的日期过滤器正在运行并向我提供此查询:

工作查询结果:

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 
FROM wp_posts 
LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 
WHERE 1=1 AND YEAR(wp_posts.post_date)=2017 
AND MONTH(wp_posts.post_date)=03 AND wp_posts.post_type = 'projects' 
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' 
OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending' 
OR wp_posts.post_status = 'private') 
GROUP BY wp_posts.ID 
ORDER BY wp_posts.post_date DESC LIMIT 0, 20
  

当我通过postmeta.meta_value过滤时,我得到一个额外的INNER JOIN   导致问题:

过滤(不完全正常)

$query->set('meta_query', array(
   array(
      'key' => 'project_cust_id',
      'value' => $project_cust_id,
      'compare' => '=' 
   )
));

查询(非工作结果)

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 
FROM wp_posts 
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 
LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 
WHERE 1=1 AND ( ( wp_postmeta.meta_key = 'project_cust_id' 
AND wp_postmeta.meta_value = '12345' ) ) AND wp_posts.post_type = 'projects' 
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' 
OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending' 
OR wp_posts.post_status = 'private') 
GROUP BY wp_posts.ID 
ORDER BY wp_posts.post_date DESC LIMIT 0, 20

当我直接查询到我的数据库时,我在下面没有得到任何结果和错误,但当我删除额外的行:INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )或当我删除行时:LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)我得到的结果为预期

  

编辑:MySQL返回错误:不是唯一值表/别名:' wp_postmeta'

我的问题是:

  • 为什么我的代码会添加另一个INNER JOIN?
  • 如何删除/阻止此额外的INNER JOIN或LEFT JOIN?

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

由于您要在where子句中的wp_postmeta表中过滤值,LEFT JOIN将像INNER JOIN一样,因为它只会返回wp_postmeta中具有匹配条件的值表。因此,拥有LEFT JOININNER JOIN或两者都不应有所作为。如果您希望联接的行为类似LEFT JOIN,则应将wp_postmeta表的任何条件添加到JOIN而不是WHERE子句。

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID 

FROM   wp_posts 

       LEFT JOIN wp_postmeta 
       ON wp_posts.ID = wp_postmeta.post_id
       AND wp_postmeta.meta_key = 'project_cust_id' 
       AND wp_postmeta.meta_value = '12345'

WHERE  1=1 AND wp_posts.post_type = 'projects' 
       AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' 
       OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending' 
       OR wp_posts.post_status = 'private') 

GROUP BY wp_posts.ID 

ORDER BY wp_posts.post_date DESC LIMIT 0, 20

答案 1 :(得分:0)

感谢大家的输入,但事实证明我的编码没有任何问题,显然有一些其他插件在我发出过滤器参数时发出GET参数,当设置此参数时返回FALSE,我通过在该插件中添加!EMPTY来修复它,之后它就像一个魅力。