V
V
Vladislav Marudenko2019-02-25 15:17:03
SQL
Vladislav Marudenko, 2019-02-25 15:17:03

How to get multiple values ​​using JOIN?

Greetings. I am writing a query with handles to extract WooCommerce products and link them to categories, but I ran into a problem.
I have the following query against the WordPress database:

SELECT 
       wp.`ID`, 
       wp.`post_title` as title, 
       wp.`post_name` as slug, 
       wtr.`term_taxonomy_id` as category, 
       wt.`name` as category_name  
FROM `wp_posts` as wp 
  INNER JOIN `wp_term_relationships` as wtr 
    ON wp.ID = wtr.object_id 
  INNER JOIN `wp_terms` as wt 
    ON wt.`term_id` = wtr.`term_taxonomy_id`
WHERE 
      `post_type` = 'product' AND 
      `post_status` = 'publish'

Everything works great, but the catch is that some products contain multiple categories in the wp_term_relationships table:
5c73dc5d80f7b942059347.png
Is there any way to get multiple table items?
Alternative solutions, advice on the case are very welcome. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pychev Anatoly, 2019-02-25
@INPVLSA

Well, your query returns several categories

spoiler
5c73e2d564597815145639.jpeg

K
Konstantin Tsvetkov, 2019-02-25
@tsklab

LEFT JOIN `wp_terms` as wt 
    ON wt.`term_id` = wtr.`term_taxonomy_id`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question