0

I have been given this great answer on how to select distinct rows from 3 of my database tables:

select p.p_id, p.`p_name`, p.brand, GROUP_CONCAT(DISTINCT c.c_id SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT s.s_id SEPARATOR ', ') as shops
from product p inner join product_category c on p.p_id = c.p_id
               inner join product_shop s on p.p_id = s.p_id
where c.c_id in (2,8)
  and s.s_id in (1,2)
group by p.p_id, p.`p_name`, p.brand

I would just like to expand on that to now also select more columns from shop and category tables. I want to add in s.s_name and c.c_name to the select results. How would I do this? I am trying with CONCAT from this answer eg:

GROUP_CONCAT(
  DISTINCT CONCAT(tags.id,',',tags.displayName) 
  ORDER BY posts.id 
  SEPARATOR ';'
)

So adding that in to my query to just add the category.c_name like this:

select p.p_id, p.`p_name`, p.brand, GROUP_CONCAT(DISTINCT CONCAT(category.c_id, category.c_name) SEPARATOR ', ') as categories, GROUP_CONCAT(DISTINCT s.s_id SEPARATOR ', ') as shops
from product p inner join product_category c on p.p_id = c.p_id
               inner join product_shop s on p.p_id = s.p_id
where c.c_id in (2,8)
  and s.s_id in (1,2)
group by p.p_id, p.`p_name`, p.brand

But for some reason that is giving this error:

1054 - Unknown column 'category.c_id' in 'field list'

How do I correctly add in more columns from category and shop tables to my select query?

Community
  • 1
  • 1
BeniaminoBaggins
  • 11,202
  • 41
  • 152
  • 287

1 Answers1

0

I had to add the shop and category tables into the query with inner join. The full sql statement is:

SELECT p.p_id, p.`p_name`, p.brand, 
GROUP_CONCAT(DISTINCT CONCAT(c.c_id,':',c.c_name) SEPARATOR ', ') as categories, 
GROUP_CONCAT(DISTINCT CONCAT(s.s_id,':',s.s_name) SEPARATOR ', ') as shops
FROM product p 
INNER JOIN product_category pc on p.p_id = pc.p_id
INNER JOIN category c ON c.c_id = pc.c_id
INNER JOIN product_shop ps on p.p_id = ps.p_id
INNER JOIN shop s ON s.s_id = ps.s_id
WHERE c.c_id in (2,8)
AND s.s_id in (1,2)
GROUP BY p.p_id, p.`p_name`, p.brand
BeniaminoBaggins
  • 11,202
  • 41
  • 152
  • 287