温馨提示:本文翻译自stackoverflow.com,查看原文请点击:mysql - Why I keep getting posts.ID unknown column while the column exists?

mysql - 为什么在该列存在时仍不断获取posts.ID未知列?

发布于 2020-03-27 11:05:48

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

查看更多

查看更多

提问者
warnerque
被浏览
163
Gordon Linoff 2019-07-03 22:19

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

发布
问题

分享
好友

手机
浏览

扫码手机浏览