SQL加入列两次

时间:2013-05-15 16:07:58

标签: mysql sql

我有以下sql:

select distinct 
p.products_image, 
pd.products_name, 
p.products_id, 
p.products_model, 
p.manufacturers_id, 
m.manufacturers_name, 
p.products_price, 
p.products_tax_class_id,
pd.products_viewed, 
group_concat(p2i.icons_id separator ",") as icons_ids, 
group_concat(pi.icon_class separator ",") as icon_class, 
IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, 
IF(s.status, s.specials_new_products_price, p.products_price) as final_price 

from products p 
left join specials s on p.products_id = s.products_id 
left join manufacturers m on p.manufacturers_id = m.manufacturers_id 
join products_description pd on p.products_id = pd.products_id 
join products_to_categories p2c on p.products_id = p2c.products_id 
INNER JOIN products_specifications ps7 ON p.products_id = ps7.products_id 
LEFT JOIN products_to_icon p2i on p.products_id = p2i.products_id 
LEFT JOIN products_icons pi on p2i.icons_id = pi.icons_id 

where p.products_status = '1' 
and pd.language_id = '1' 
AND ps7.specification in ('Cotton' , 'Fireproof' ) 
AND ps7.specifications_id = '7' 
AND ps7.language_id = '1' 
and p2c.categories_id = '21' 

group by p.products_id order by pd.products_name

当1个产品只有1个规格时,这非常有效。但是,当产品具有2种规格(棉花和防火)时,product_icons正在翻倍。

我选择的是不同的,但因为它有2个规格,它检索2x图标,我不知道为什么(在我看来,在选择图标ID两次之前,我应该注意这一点。)

我错过了什么?

更新以澄清:

我从上面的查询得到的结果如下所示: http://i.imgur.com/aD6JM0q.png

请注意第3行的列icon_id显示相同的icon_ids两次5,1,5,1

我的目标是只显示那些ID,因此它应该是5,1

我选择的规格越多,由于属于多种不同规格的产品,重复次数就越多。

此处进一步澄清products_to_icons和products_icons表的一些示例图像

Products_to_icons:http://i.imgur.com/gBhlCri.png products_icons:http://i.imgur.com/1134Rb1.png

1 个答案:

答案 0 :(得分:0)

您正在进行群组连接,但没有实际的群组可以使用它作为基础。查询如何知道如何破坏组以为您提供所需的多个帐户。