运行 查询输出中的 cfquery

Run a cfquery inside of a query output

当我尝试 运行 上一个查询的输出中的 cfquery 时,我得到了奇怪的意外结果。

示例:

<cfoutput query="reportInfo">
  <tr>
    <td>#id#</td>
    <td>#name#</td>    
    <cfif Status EQ 'Complete'>
      <cfquery name="submitInfo" datasource="RC">
        SELECT  *
        FROM    Action_Log
        WHERE Form_ID = '#id#'
        AND Action = 'Complete' OR Action = 'Saved'
      </cfquery>    
      <cfset startStamp = submitInfo.Action_Time>
      <cfoutput>startStamp</cfoutput>    
      <td>#startStamp#</td>
    <cfelse>
      <td>No Completion Date</td>
    </cfif>
  </tr>
</cfoutput>

当 "StartStamp" 输出到页面时,它会针对循环中的每个计数显示一次,并且会针对每个 ID 执行此操作,因此有很多额外内容。

我认为每次包含查询 (reportInfo) 输出循环时应该只 运行 一次 submitInfo 查询,但那没有发生。

(根据评论扩展...)

<cfoutput>startStamp</cfoutput>

不确定您要完成什么,但您应该摆脱内部 cfoutput tags。只有在使用(经常被误解)<cfoutput group="..."> feature. It is normally used to eliminate duplicates from sorted data. However, if the data is not sorted properly - or is grouped incorrectly - it can produce the kind of results you described. (If you are not familiar with grouping, see this example of creating an A-Z type listing).

时才需要这些

话虽如此,应避免在循环内查询。大多数时候,您可以使用简单的 JOIN 获得相同的结果。在不了解第一个查询的更多信息的情况下,我认为您没有理由不能在此处执行此操作。

在 psuedo-sql 这些方面。它使用 OUTER JOIN 检索第一个 table 中的所有记录,但仅检索 Action_Log 中具有匹配 ID 和状态 "Complete" 或 "Saved" 的值.

SELECT  t1.ID
        , t1.Name
        , al.Action_Time AS CompletionDate
FROM    SomeTable t1
      LEFT JOIN Action_Log al 
                ON al.Form_ID = t1.ID 
                AND t1.Status = 'Complete'
                AND al.Action IN ('Complete','Saved')