0

我想将一组查询合并到一个查询中

我试过这个

<cfquery name="MergedData" dbtype="query">
    <cfloop from="1" to="#arrayLen(arData)#" index="k"> 
        SELECT *
        FROM    arData[k]
        <cfif k LT ArrayLen(arData)>UNION</cfif>
    </cfloop>
    ORDER BY EID
</cfquery>

我收到一个看起来像的错误

<br><b>Query Of Queries syntax error.</b><br> Encountered "[k]. 
4

4 回答 4

2

Try an alternative way of looping over your array. You need to create your own counter though to figure out the logic of if you need to keep appending 'UNION' to your SQL statement.

<cfset i = 1>
<cfquery name="MergedData" dbtype="query">
    <cfloop index="k" array="#arData#"> 
        SELECT *
        FROM    k
        <cfif i LT ArrayLen(arData)>UNION</cfif>
        <cfset i++>
    </cfloop>
    ORDER BY EID
</cfquery>

NB: you wouldn't need to calculate a counter yourself if you're using Railo instead of Adobe CF, as you can then do both index and item like so, as Peter mentioned in the comments above:

<cfloop index="i" item="k" array="#arData#"> 
于 2014-02-03T09:25:21.277 回答
1

如果您想通过函数式编程完成此操作,可以使用Underscore.cfc 库(需要 CF 10+ 或 Railo 4+):

// instantiate Underscore library
_ = new Underscore();

// convert the array of queries to a single array of structs
mergedArray = _.reduce(arrayOfQueries, function (memo, query) {
  // convert current query to an array of structs
  //   and concatenate it to the rest of the result
  return _.concat(memo, _.toArray(query));
}, []);

// convert the array of structs back to a query
mergedQuery = _.toQuery(mergedArray);

该解决方案利用reduce()将查询数组组合成单个结构数组。传递给的匿名函数使用reduce()将查询数组中的每个查询转换为结构数组toArray(),然后将该数组与结构数组的其余部分(memo值)连接起来。

将查询数组转换为单个结构数组后,将其转换回查询是一件简单的事情toQuery()(假设这是必要的)。

注意:我写了下划线库

于 2014-02-04T04:57:16.530 回答
0

这就是最终的工作

<cfquery name="local.qryMergedData" dbtype="query">
    <cfloop array="#arguments.Data#" index="k">
        <cfset local.currentIndex++>
        <cfset setvariable("Data_#local.currentIndex#", k)>

        SELECT *
        FROM   Data_#local.currentIndex#
        <cfif local.currentIndex LT local.MaxIndex>UNION</cfif>
    </cfloop>
    ORDER BY EID
</cfquery>  

我真的不喜欢我在 a 中设置一个变量<cfquery>,但至少它只是一个查询

于 2014-02-03T16:51:19.823 回答
0

试试这样:

    <cfsavecontent variable="testing">
    <cfset j = 1>
    <cfloop array="#test#" index="i">
        SELECT id FROM #i# LIMIT 10
        <cfif j LT ArrayLen(test)> UNION </cfif>
        <cfset j++>
    </cfloop>
</cfsavecontent>

<cfquery name="qTest" datasource="#application.dsn#">
    #testing#
</cfquery>
于 2014-02-03T14:45:56.297 回答