2014-03-05 45 views
1

我想列出每个客户购买的产品,但如果他们在不同的场合买了相同的项目,我希望它排除它。这是我到目前为止有:选择不同的左加入只有一列

Select c.field_id_33 AS email, o.order_id, Group_concat(o.entry_id) AS Products,group_concat(t.title),group_concat(t.url_title) from finn_cartthrob_order_items o 
LEFT JOIN finn_channel_data c 
ON c.entry_id=o.order_id 
LEFT JOIN finn_channel_titles t 
ON o.entry_id=t.entry_id 
GROUP BY email 

本步骤是:

screenshot

基本上我只需要一个产品上市一次,如果他们已经购买了它,不管多少次他们已经购买了它。我将如何做到这一点?

+0

你想让你的结果看起来像什么?另外,最佳做法是将SELECT子句中的每个列的GROUP BY都不包含聚合函数。 – AgRizzo

+0

你的屏幕截图是如何丢失电子邮件列和其他人的? – MatBailie

+0

由于数据库已满,我不想拍摄出一堆电子邮件地址。 – nick

回答

2

可以在GROUP_CONCAT函数中使用DISTINCT,使用Group_concat baware的事实它有1024个字符给他们组的默认限制,但它可以增加

Select c.field_id_33 AS email, o.order_id, 
Group_concat(DISTINCT o.entry_id) AS Products, 
group_concat(DISTINCT t.title), 
group_concat(DISTINCT t.url_title) 
from finn_cartthrob_order_items o 
LEFT JOIN finn_channel_data c 
ON c.entry_id=o.order_id 
LEFT JOIN finn_channel_titles t 
ON o.entry_id=t.entry_id 
GROUP BY email 

从文档结果被截断最大长度为 ,由group_concat_max_len系统变量给出,该系统变量的默认值为 ,值为1024.虽然有效的 返回值的最大长度受限于 max_allowed_包。在运行时更改 group_concat_max_len的值的语法如下,其中val是一个无符号整数 :

SET [GLOBAL | SESSION] group_concat_max_len = val;

+1

谢谢,我没有意识到我可以在group_concat中使用不同的内容 – nick

0

正如你可以select关键字后使用distinct,你也可以用它聚合函数(包括group_concat)内,聚合每个不同的值只有一次:

Select 
    c.field_id_33 AS email, o.order_id, 
    Group_concat(DISTINCT o.entry_id) AS Products, 
    group_concat(DISTINCT t.title), 
    group_concat(DISTINCT t.url_title) 
from finn_cartthrob_order_items o 
LEFT JOIN finn_channel_data c 
ON c.entry_id=o.order_id 
LEFT JOIN finn_channel_titles t 
ON o.entry_id=t.entry_id 
GROUP BY email 
0

你有没有想过使用ROW_NUMBER通过PARTITION BY?

下面是一个示例。

SELECT * 
    FROM (SELECT order_id, 
      entry_id, 
      ROW_NUMBER() OVER (PARTITION BY entry_id 
       ORDER BY entry_id) AS ProductCount 
      FROM finn_cartthrob_order_items 
      ) AS Products 
WHERE ProductCount = 1 
ORDER BY Products.order_id 

这应该返回每个entry_id的第一个order_id和entry_id。它的功能在概念上与此类似。

SELECT TOP 1 * 
    FROM finn_cartthrob_order_items 
    WHERE entry_id = @Specific_entry_id 

您可能需要在Over(Partition By)中包含一些左连接。