如何将两个单独的查询合并/合并为一个?

问题描述 投票:0回答:1

我有一些旧代码,其中一个页面的查询速度非常慢。有两个引起了我的注意,因为它们非常相似(几乎完全相同)。唯一的区别是WHERE CLAUSE中的一行。这是一个例子:

-- Query 1
SELECT * -- Just for testing purpose I use * 
FROM Table 1
WHERE rec_id = #selected_id#
   <cfif userid is not "6">
       AND store_id = '#url.storedid#' -- I do not use cfqueryparam for testing purpuse
   </cfif>

-- Query 2
SELECT * -- Just for testing purpose I use * 
FROM Table 1
WHERE rec_id = #selected_id#
   <cfif userid is not "6">
       <cfif session.market_id is 4>
           AND store_id IN ('01','02','03')
       <cfelse>
           AND store_id = '#url.storedid#'
       </cfif>
   </cfif>

正如您所看到的,这两个查询之间的唯一区别在于WHERE块中的cfif子句。我想知道是否有办法将这两个查询合二为一?唯一用于检查两个结果集之间差异的列是TOTAL列。如果有人知道如何实现这一点,请告诉我。谢谢。

sql join coldfusion sybase coldfusion-11
1个回答
0
投票

这不一定是最好的方法,但它会回答你问的问题是如何用单个查询实现相同的逻辑。

SELECT * -- Just for testing purpose I use * 
FROM Table 1
WHERE rec_id = #selected_id#
   <cfif userid is not "6" and session.market_id is 4>
           AND store_id IN ('01','02','03')
       <cfelseif userid is not "6">
           AND store_id = '#url.storedid#'    
   </cfif>

请记住,这种方法的逻辑略有不同,因为只有一个查询变量。评论表明您可能需要两个变量,在这种情况下这种方法可行。

Query1是您问题中的第一个。

<cfif userid is not "6" and session.market_id is 4>
<cfquery name = Query2 dbtype="query">
select *
from Query1
where store_id IN ('01','02','03')
</cfquery>
<cfelse>
<cfset Query2 = Query1>
</cfif>
© www.soinside.com 2019 - 2024. All rights reserved.