如何从 CFloop 查询结果中删除行

kmo*_*s84 1 coldfusion cfquery cfloop

我正在使用循环查询并在存在要连接的记录时连接表。

当没有记录要加入该行时,有没有办法阻止该行完全返回?

编辑:我错过了其中的 if 语句。我正在循环记录并检查设置选项,如果该设置选项存在于记录中并且查询“someRecord”中没有相应的记录,那么这些是我不想返回的记录。

<cfloop query="myquery">
    <cfif listfindnocase(myquery.setup_option,"required_information")>
        <cfquery name="someRecord" dbtype="query">
            select * from second_table
            where key_id = '#myquery.key_id#'
        </cfquery>
        <cfif someRecord.recordcount eq 0>

        <!--- Need something here to remove this row from returning in the query --->

        </cfif>
    </cfif>
</cfloop>
Run Code Online (Sandbox Code Playgroud)

Ada*_*ron 5

好的,这里的标准答案是:不要在 CFML 中执行此操作,而是在 DB 上执行此操作。CF 用于字符串生成,而不是数据操作。

这个问题有点误导,因为它最初询问如何从查询中删除行,但事实证明,这不是要求(请参阅对该问题的评论)。我已经在下面进一步回答了这个问题。

要简单地退出循环迭代,请使用<cfcontinue>. 这会立即结束循环的当前迭代,并返回到代码块的顶部并开始下一次迭代。使用您自己的代码示例:

<cfloop query="myquery">
    <cfif listfindnocase(myquery.setup_option,"required_information")>
        <cfquery name="someRecord" dbtype="query">
            select * from second_table
            where key_id = '#myquery.key_id#'
        </cfquery>
        <cfif someRecord.recordcount eq 0>
            <cfcontinue>
        </cfif>
        <!--- handle the rows you *do* want to process here --->
    </cfif>
</cfloop>
Run Code Online (Sandbox Code Playgroud)

然而,要回答如何从查询中删除行的问题,没有优雅的方法来做到这一点。你有两个不优雅的选择:

// pseudocode, for brevity
newQuery = queryNew(oldQuery.columnList)
loop (oldQuery)
    if the row is not wanted
        continue
    /if
    add a row to newQuery
    add the row data to newQuery
/loop
Run Code Online (Sandbox Code Playgroud)

或者:

listOfRowsToExclude = someMechanismToArriveAtSaidList()
<cfquery name="newQuery" type="query">
    SELECT   *
    FROM     oldQuery
    WHERE    id NOT IN (listOfRowsToExclude)
    ORDER BY [same clause as for oldQuery]
</cfquery>
Run Code Online (Sandbox Code Playgroud)

然而,到目前为止,最好的建议是在数据所属的数据库中进行数据处理。您不应该将这种逻辑放入 a) 您的 CFML 应用程序中;b)在你的视图代码中,我怀疑这一切都是在哪里发生的。

将逻辑与显示分开。并将数据处理逻辑与应用程序逻辑分开。