SELECT语句中的GROUP_CONCAT

时间:2011-12-15 13:31:23

标签: php mysql join group-concat

我对带有GROUP_CONCAT的SQL语句有一个小问题。

我有这样的声明:

SELECT ni.*, GROUP_CONCAT(newsletter_item_receivers.value) AS receivers, nf.*, GROUP_CONCAT(nm.mailgroup_name) AS mailgroups
FROM newsletter_items ni
INNER JOIN newsletter_fields nf ON (nf.field_letter_uid = ni.letter_id)                                                          
LEFT JOIN newsletter_item_receivers ON (newsletter_item_receivers.letter_id = ni.letter_id)
INNER JOIN newsletter_mailgroups nm ON (FIND_IN_SET(nm.mailgroup_id, newsletter_item_receivers.value))
WHERE nf.field_name = 'letter_headline' AND ni.template = '". $template ."' 
GROUP BY ni.letter_id

我做错了什么,因为我的输出搞砸了。

我有4张桌子:

包含以下列的newsletter_items:

letter_id (int)
letter_date (int)
template (varchar)
status (int)

和newsletter_item_receivers 有这些列:

rid (int)
letter_id (int)
value (int)

newsletter_mailgroups

mailgroup_id (int)
mailgroup_name (varchar)

newsletter_fields

field_uid (int)
field_name (varchar)
field_content (text)
field_letter_uid (int)

我几乎得到了我想要的输出,但我的邮件组显示错误。我希望它显示为

A组,C组,但显示为

A组,C组,A组,C组,C组 当我的newsletter_item_receivers表包含这个:

rid | letter_id | value
1   | 1         | 2
2   | 1         | 3
3   | 2         | 1

newsletter_item_receivers.letter_id指的是newsletter_items.letter_id和 newsletter_item_receivers.value是指newsletter_mailgroups.mailgroup_id

有人能看出我做错了吗?

1 个答案:

答案 0 :(得分:2)

试试这个: -

group_concat( DISTINCT newsletter_item_receivers.value 
              ORDER BY newsletter_item_receivers.value)

group_concat( DISTINCT nm.mailgroup_name 
              ORDER BY nm.mailgroup_name)