为什么在存在该列的情况下仍不断获取posts.ID未知列?

时间:2019-07-03 14:14:03

标签: mysql sql wordpress woocommerce

这是我下面的WooCommerce SQL查询。我不断收到错误消息,

Unknown column 'posts.ID' is 'on clause' 

但是我的posts.ID列确实存在。

SELECT DISTINCT posts.ID as product_id, posts.post_parent as parent_id FROM wp_posts posts, 
wp_terms terms, wp_term_relationships term_relationships LEFT JOIN wp_wc_product_meta_lookup 
wc_product_meta_lookup ON posts.ID=wc_product_meta_lookup.product_id WHERE 
posts.ID=term_relationships.object_id AND term_relationships.term_taxonomy_id=terms.term_id 
AND terms.name!='exclude-from-catalog' AND posts.post_type IN ('product') 
AND (  ( ( posts.post_title LIKE '%bruno%') OR ( posts.post_excerpt LIKE '%bruno%') 
OR ( posts.post_content LIKE '%bruno%' ) OR ( wc_product_meta_lookup.sku LIKE '%bruno%' ) )) 
AND posts.post_status IN ('publish') ORDER BY posts.post_parent ASC, posts.post_title ASC;

1 个答案:

答案 0 :(得分:1)

从不FROM子句中使用逗号。 始终使用正确的,明确的,标准 JOIN语法。

因此,将查询正确编写为:

SELECT DISTINCT p.ID as product_id, p.post_parent as parent_id
FROM wp_posts p JOIN
     wp_term_relationships
     ON p.id = tr.object_id JOIN
     wp_terms t
     ON tr.term_taxonomy_id = t.term_id LEFT JOIN
     wp_wc_product_meta_lookup pml
     ON p.ID = pml.product_id
WHERE t.name <> 'exclude-from-catalog' AND
      p.post_type IN ('product') AND 
      (p.post_title LIKE '%bruno%' OR
       p.post_excerpt LIKE '%bruno%' OR
       p.post_content LIKE '%bruno%'  OR 
       pml.sku LIKE '%bruno%'
      ) AND
      p.post_status IN ('publish')
ORDER BY p.post_parent ASC, p.post_title ASC;

注意:

  • 具体的问题是,影响标识符的范围。您不能在逗号后面的ON子句中从逗号前面引用表别名。
  • 我认为没有理由重复表名。
  • 使用表别名很好,但是如果别名较短,则查询会更简单。