2012-11-28 21 views
1

我已經問過一個問題(Query with grouped results by column (SQL Server))。並得到了一些適用於SQL服務器的答案,但我無法讓他們作爲QoQ的一部分工作。結果CF有一些小的限制,如不能使用INNER JOINcoldfusion QoQ和條件

我試圖實現的是得到一個查詢可以有多個項目名稱爲同一項目,但是當我打電話給我QoQ,我希望它過濾(保留)與語言ID相匹配的項目(如果有),如果缺失,則默認爲另一項目。

我這樣做了幾個查詢,所以我想要在一個函數中的代碼,我插入查詢,uniqueColumn名稱languageId。

因爲我不能使用內部連接,而且我遇到了一些條件問題,所以我想創建一個只有匹配languageId的第二個表,然後添加另一個表中缺少的條目。

有沒有辦法在一個查詢中做到這一點?

回答

0

您可以使用Q的Q進行內部連接。您只能使用關鍵字「連接」。你必須在where子句中加入你的查詢。類似這樣的:

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

Q聯合查詢的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)) 

但正確的語法,當然queryparams

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>