warnerque
warnerque

Reputation: 83

Why I keep getting posts.ID unknown column while the column exists?

This is my WooCommerce SQL query below. I keep getting the error,

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

but my posts.ID column does exist.

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;

Upvotes: 1

Views: 442

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269663

Never use commas in the FROM clause. Always use proper, explicit, standard JOIN syntax.

So, write the query correctly as:

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;

Notes:

  • The specific problem is that , affects the scoping of identifiers. You cannot reference a table alias from before the comma in an ON clause after the comma.
  • I see no reason to duplicate table names.
  • Using table aliases is good, but the query is simpler if the aliases are shorter.

Upvotes: 1

Related Questions