2

我正在尝试使用以下内容进行查询。出于问题的目的,我已尽可能简化了查询。它基本上适用于我正在编写的电子邮件计划应用程序。

两张桌子。一封电子邮件可以属于一个特定的时间表。一个时间表包括几封电子邮件。每封已发送的电子邮件都标有特定的步骤编号。第 1 步、第 2 步、第 3 步、第 4 步、第 5 步

email_schedular (id, datecreated, recipient)
email(id, email_schedular_id, text, subject, sent, stepNumber)

现在我要做的是在报告中确定是否已发送步骤。我已经尝试过了,但我不确定我是否以正确的方式进行?

SELECT
  ed.id,
  ed.datecreated
  ed.recipient
  if(e.stepNumber= 1, 'Y', 'N')  AS step_1_sent,
  if(e.stepNumber= 2, 'Y', 'N')  AS step_2_sent,
  if(e.stepNumber= 3, 'Y', 'N')  AS step_3_sent,
  if(e.stepNumber= 4, 'Y', 'N')  AS step_4_sent
FROM 
  email_echedular ed
JOIN email e ON (e.email_echedular_id = ed.id)
GROUP BY ed.id
4

2 回答 2

1

不要使用Nfor not sent,而是使用NULL. 然后,当您对它们进行分组时,您可以获取MAX()每个值并将 NULL 消除到一行。最终结果应该是每行ed.id一个Yes,用于已发送的步骤和NULL未发送的步骤。

SELECT
  ed.id,
  ed.datecreated
  ed.recipient
  MAX(if(e.stepNumber= 1, 'Y', NULL)) AS step_1_sent,
  MAX(if(e.stepNumber= 2, 'Y', NULL)) AS step_2_sent,
  MAX(if(e.stepNumber= 3, 'Y', NULL)) AS step_3_sent,
  MAX(if(e.stepNumber= 4, 'Y', NULL)) AS step_4_sent
FROM 
  email_schedular ed
  LEFT JOIN email e ON (e.email_schedular_id = ed.id)
GROUP BY ed.id

如果您真的不希望 aNULL用于未发送的列,则可以将它们包装起来COALESCE()以替换NULLN

SELECT
  ed.id,
  ed.datecreated
  ed.recipient
  COALESCE(MAX(if(e.stepNumber= 1, 'Y', NULL)), 'N') AS step_1_sent,
  COALESCE(MAX(if(e.stepNumber= 2, 'Y', NULL)), 'N') AS step_2_sent,
  COALESCE(MAX(if(e.stepNumber= 3, 'Y', NULL)), 'N') AS step_3_sent,
  COALESCE(MAX(if(e.stepNumber= 4, 'Y', NULL)), 'N') AS step_4_sent
FROM 
  email_schedular ed
  LEFT JOIN email e ON (e.email_schedular_id = ed.id)
GROUP BY ed.id

编辑更改为LEFT JOIN并固定连接条件...

于 2012-07-10T18:28:05.010 回答
0
SELECT
  ed.id,
  ed.datecreated
  ed.recipient
  if(e.stepNumber= 1, 'Y', 'N')  AS step_1_sent,
  if(e.stepNumber= 2, 'Y', 'N')  AS step_2_sent,
  if(e.stepNumber= 3, 'Y', 'N')  AS step_3_sent,
  if(e.stepNumber= 4, 'Y', 'N')  AS step_4_sent
FROM 
  email_echedular ed
JOIN email e ON (e.email_echedular = e.id)
GROUP BY ed.id

在这条线上JOIN email e ON (e.email_echedular = e.id)谁是e.email_Echedular?将其更改为JOIN email e ON (e.email_Schedular = e.id)

于 2012-07-10T18:37:42.667 回答