查询表基于输入参数

时间:2017-01-13 14:52:52

标签: mysql conditional

我正在尝试编写的查询的输入参数。基本上,if mostRecentSnapshot == true然后我想只选择流程运行中的最新记录(基本上是where max(creationDate))和if mostRecentSnapshot == false然后select creationDate和其他列。

对我而言,在if条款中执行此from语句是有道理的,但我认为这不可行。通常我会使用CTE,但我在MySQL中不存在。

实现这一目标的最佳方法是什么?

这将是这样的:

SELECT
CASE mostRecentSnapshot WHEN FALSE THEN 
(
processauditheader.creationDate as processCreationDate,
processauditheader.processName,
processauditheader.processType,
processauditheader.processHost,
processauditheader.processDatabase,
processauditheader.tableAudited,
processauditheader.processInvokedByName,
processauditheader.processInvokedByType,
processauditheader.processInvokedByDatabase,
processauditheader.processIntervalValue,
processauditheader.processIntervalField,
processauditheader.auditScenarios,
processaudititerationdetail.creationDate as iterationDate,
processaudititerationdetail.connectionId,
processaudititerationdetail.processDate,
processaudititerationdetail.tableRowCount,
processaudititerationdetail.tableRowCountLastDay,
processaudititerationdetail.previousProcessAuditIterationDetailID,
processauditmetricdetail.creationDate,
processauditmetricdetail.processAuditIterationDetailID,
processauditmetricdetail.auditMetric,
processauditmetricdetail.auditTotal,
processauditmetricdetail.auditExample
)
WHEN TRUE THEN 
(
((SELECT MAX(processaudititerationdetail.creationDate) as maxSnapshot,
processaudititerationdetail.id
from reporting_audit.processaudititerationdetail
group by processaudititerationdetail.creationDate) mostRecent

JOIN reporting_audit.processaudititerationdetail ON mostRecent.id = processaudititerationdetail.id)
)
END

FROM reporting_audit.processauditheader

JOIN processaudititerationdetail ON processaudititerationdetail.processAuditHeaderID = processauditheader.id
LEFT JOIN processauditmetricdetail ON processauditmetricdetail.processAuditIterationDetailID = processaudititerationdetail.id

1 个答案:

答案 0 :(得分:1)

查询只能返回一组固定的列。也许以下是您想要的:

select paid.*
from reporting_audit.processaudititerationdetail paid
where (not v_mostRecentSnapshot) or
      paid.creation_date = (select max(paid2.creationDate from reporting_audit.processaudititerationdetail paid2);

它将从表中选择所有记录,或仅选择具有最新creationDate的记录。