GroupBy ID,但保留多个值

时间:2018-10-02 15:13:09

标签: mysql

我有以下MySQL表:

+----------+----------+---------+-------------+------------+----------+----------+-----------+
| queue_id | email_id | user_id | customer_id |  send_date | campaign | approved | scheduled |
+----------+----------+---------+-------------+------------+----------+----------+-----------+
|    1     |    1     |    1    |      1      | 2018-10-30 |     1    |     1    |     1     |
|    2     |    1     |    2    |      1      | 2018-10-30 |     1    |     1    |     1     |
|    3     |    2     |    1    |      1      | 2018-11-02 |     1    |     1    |     1     |
|    4     |    2     |    2    |      1      | 2018-11-02 |     1    |     0    |     1     |
|    5     |    2     |    3    |      1      | 2018-11-02 |     1    |     1    |     1     |
+----------+----------+---------+-------------+------------+----------+----------+-----------+

其中email_iduser_idcustomer_id都是外键。

我需要做的是返回send_datesubject(属于email引用的email_id表的一部分)和name (属于business引用的user_id表的一部分),但仅适用于approved列为true的列。最终的想法是在HTML表中向用户显示数据,该表如下所示(使用提供的示例数据):

+--------------------+--------------------------+---------------+
| October 30th, 2018 | Subject for email_id "1" | View Approved |
| November 2nd, 2018 | Subject for email_id "2" | View Approved |
+--------------------+--------------------------+---------------+

只要用户单击“查看已批准”单元格,就会显示批准该特定电子邮件的所有公司名称。

我尝试使用以下查询,但它仅在name列中返回一个值:

SELECT
  DATE_FORMAT(q.`send_date`, "%M %D, %Y") AS `date_visited`,
  e.`subject`,
  b.`name`
FROM
  `email_queue` AS q
INNER JOIN
  `email`    AS e ON q.`email_id`    = e.`email_id`
INNER JOIN
  `user`     AS u ON q.`user_id`     = u.`user_id`
INNER JOIN
  `business` AS b ON u.`business_id` = b.`business_id`
WHERE
  q.`approved` = true
GROUP BY
  e.`email_id`
ORDER BY
  q.`send_date` DESC

如何构造查询的结构,使其返回name列中的所有公司名称,而不仅仅是一个?

1 个答案:

答案 0 :(得分:1)

您可以使用带有Group_Concat()函数和Distinct子句的逗号分隔的字符串来获取所有不确定的商业名称。

尝试:

GROUP_CONCAT(DISTINCT b.`name` SEPARATOR ',') AS name  

代替:

b.`name`

注意:

  • 如果不会有重复的Distinct(对于特定的user_id),则可以避免使用email_id子句,从而确保b.name也是唯一的。
  • 您还可以使用任何分隔符来代替逗号。例如:要将分隔符用作管道字符|,则将查询写为:

    GROUP_CONCAT(DISTINCT b.名称SEPARATOR '|') AS name