Mysql将两个group_concat结果相互比较

时间:2015-03-18 19:45:17

标签: php mysql compare group-concat having

我有一张表events和一张表invoices

每个event最多可以有5个invoices(发票有一个event_id,只能有一个事件)

每张发票都有两个字段,“已取消”和“paperwork_received_datestamp”。我们将“完全完成的事件”视为每个未取消的发票,其中包含为该字段输入的日期。我需要显示一个只有“完全完成的事件”的列表。

我有这个查询

SELECT
     Event.id, 
     GROUP_CONCAT(Invoice.cancelled) AS "cancelled_status",
     GROUP_CONCAT(IF(Invoice.paperwork_received_datestamp IS NOT NULL, "installed", "not_installed")) AS "paperwork_status"
FROM
     `events` `Event`
     LEFT JOIN invoices Invoice ON Invoice.event_id = Event.id
WHERE
     YEAR(Invoice.submit_date) = 2015
GROUP BY
     Event.id

这产生了诸如

之类的输出
Event ID ---- cancelled_status---- paperwork_status

 23562 --------no,no,no ------------installed,installed,installed (this row should show up)

 21563 -------no,no,yes -------------installed,installed,not_installed (this row should show up)

 24672 --------no,no ----------------installed,not_installed (this row shouldn't show up)

25784 ----------yes,yes -------------not_installed,not_installed (this row shouldn't show up)

我能想到的唯一方法就是在PHP的group_concat字段中使用explode并循环遍历每一行并使用一些逻辑并排除我想要排除的行以创建列表。我宁愿在mySQL中这样做。有任何想法吗?

1 个答案:

答案 0 :(得分:1)

对不起伙计们,我找到了答案。 (我愿意接受更好的方法)

SELECT
     GROUP_CONCAT(IF(Invoice.cancelled = "NO" && Invoice.paperwork_received_datestamp IS NULL, "incomplete", "complete")) AS "test"
FROM
     `events` `Event`
      LEFT JOIN invoices Invoice ON Invoice.event_id = Event.id
WHERE
      YEAR(Invoice.submit_date) = 2015
GROUP BY
      Event.id
 HAVING 
      INSTR(test, 'i') = 0 /* removes all incompletes */