【问题标题】:Why I keep getting posts.ID unknown column while the column exists?为什么我在列存在时不断收到posts.ID 未知列?
【发布时间】:2019-07-03 14:14:03
【问题描述】:

这是我下面的 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;

【问题讨论】:

    标签: mysql sql wordpress woocommerce


    【解决方案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 子句中引用逗号前的表别名。
    • 我认为没有理由重复表名。
    • 使用表别名很好,但如果别名更短,查询会更简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-07
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多