coldfusion QoQ和条件

时间:2012-11-28 23:58:11

标签: coldfusion qoq

我前一段时间问了一个问题(Query with grouped results by column (SQL Server))。并获得了一些可以在SQL服务器上运行的答案,但我不能让它们作为QoQ的一部分工作。原来CF有一些小的限制,比如无法使用INNER JOIN

我想要实现的是获得一个可以为同一个项目设置多个项目名称的查询,但是当我调用我的QoQ时,我希望它过滤(保留)与语言ID匹配的项目,如果有的话,如果缺少则默认为另一个。

我正在为多个查询执行此操作,因此我尝试将代码放在函数中,我插入查询,uniqueColumn名称是languageId。

因为我不能使用内连接而且我遇到了一些条件问题,所以我想创建一个只有匹配的languageId的第二个表,然后添加另一个表中缺少的条目。

有没有办法在一个查询中执行此操作?

2 个答案:

答案 0 :(得分:0)

您可以使用Q的Q进行内部联接。您不能使用关键字“join”。您必须在where子句中加入您的查询。像这样:

select whatever
from query1, query2
where query1.field1 = query2.field2
etc

Q联合查询的Q与您使用数据库查询的方式相同。要做这样的事情,“我希望它过滤(保留)与语言ID匹配的项目(如果有的话),如果缺少则默认为另一项。”,代码类似于

select query2.actual_value
from query1, query2
where query1.field1 = query2.field2
etc
union
select default_value
from query1
where field1 not in( ValueList(query2.field2) )

但当然使用正确的语法和查询框架

答案 1 :(得分:0)

最终做了很多:与原始解决方案相比,这加快了它的速度:)

<cffunction name="getUniqueName" output="true" returntype="Query">
    <cfargument name="q" Type="query" required="true">
    <cfargument name="uniqueColumn" Type="string" required="false" default="ID">
    <cfargument name="languageId" Type="string" required="false" default="">

    <cfif languageID EQ ''><cfset languageID = #session.langID#></cfif> <!--- default language id to user language id --->

    <!--- Get all items that match language ID --->
    <cfquery dbtype="query" name="qwLangId">
        SELECT *
        FROM 
          q
        WHERE 
          languageid = #languageId#  
    </cfquery>

    <!--- Get list of IDs for items found --->
    <cfset usedIDs = ArrayToList(qwLangId[uniqueColumn])>

    <cfif usedIDs NEQ ''>
        <!--- get all items that were not found in matched query --->
        <cfquery dbtype="query" name="qMissing">
            SELECT *
            FROM 
              q
            WHERE #uniqueColumn# NOT IN(#usedIDs#)
        </cfquery>

        <!--- combine items in a new query --->
        <cfquery dbtype="query" name="langQ">
            SELECT * FROM qwLangId
            UNION
            SELECT * FROM qMissing
            ORDER BY #uniqueColumn#
        </cfquery>
        <cfreturn langQ>
    <cfelse>
        <cfreturn q>
    </cfif>

</cffunction>