我已经获得this great answer关于如何从我的3个数据库表中选择不同的行:
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
我只想扩展它,现在还从shop
和category
表中选择更多列。我想在s.s_name
和c.c_name
中添加选择结果。我该怎么做?我正在尝试使用来自this answer的CONCAT,例如:
GROUP_CONCAT(
DISTINCT CONCAT(tags.id,',',tags.displayName)
ORDER BY posts.id
SEPARATOR ';'
)
因此,将其添加到我的查询中,只需添加category.c_name,如下所示:
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
但出于某种原因,这是错误的:
1054 - 未知栏' category.c_id'在'字段列表'
如何正确地将类别和商店表格中的更多列添加到我的选择查询中?
答案 0 :(得分:0)
我必须使用shop
将category
和inner join
表添加到查询中。完整的sql语句是:
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