我有两个coldfusion查询,如下面的查询返回不同的列以及日期列。
<cfquery name="qry1" datasource="test">
select title, name, id, test_date from table1 , table2
</cfquery>
<cfquery name="qry2" datasource="test">
select headline, itemid, create_dt from table3 , table4
</cfquery>
我想加入这两个查询的结果,并且在最终查询中需要按日期desc排序结果(注意:2个查询中返回的日期是2个不同的列)。我知道可以选择联合所有这两个查询,我不想使用它,因为它会减慢请求。任何想法以不同的方式实现这一目标。
<CFQUERY NAME="getDetails" DBTYPE="query">
SELECT emp_id, url_shortcut, title, name, join_dt
,'' as item_id,'' as batch_id, '' as item_text
FROM get_related_info_one
UNION ALL
SELECT to_number('') as emp_id, '' as url_ shortcut, '' as title, '' as name
,item_date as join_dt, item_id, batch_id, item_text
FROM get_related_info_two
</CFQUERY>
我收到错误: 查询查询语法错误。 遇到“(。 选择语句不正确, 期待'从',但遇到'('相反, select语句应该有一个'FROM'结构。 不知道我在这里缺少什么。
答案 0 :(得分:1)
只要列类型相同,你就可以UNION它们。
<cfquery name="qry1" datasource="test">
select title, name, id, test_date
from table1 , table2
UNION
select headline, '' as name, itemid, create_dt
from table3 , table4
ORDER BY test_date
</cfquery>
答案 1 :(得分:1)
如果您正在寻找基于CF的方法(特别是在使用内存查询查询时),Ben Nadel编写了一个QueryAppend UDF。
https://www.bennadel.com/blog/114-coldfusion-queryappend-qone-qtwo.htm
我最近做了一些调整,以便NULL日期(被ColdFusion视为“空”)不会被错误地转换。
https://gist.github.com/JamoCA/5a2adb52cbeb4e15337a7d899222072e
<!--- 7/5/2006 QueryAppend By Ben Nadel https://www.bennadel.com/blog/114-coldfusion-queryappend-qone-qtwo.htm
1/5/2017 New "EmptyAsNull" option to prevent NULL values (dates & numbers) from being incorrectly recast
to an invalid "empty string" by ColdFusion's Query-of-Queries and throwing "Error casting an object
of type to an incompatible type" error. --->
<cffunction name="QueryAppend" access="public" returntype="void" output="false" hint="This takes two queries and appends the second one to the first one. This actually updates the first query and does not return anything.">
<cfargument name="QueryOne" type="query" required="true">
<cfargument name="QueryTwo" type="query" required="true">
<cfargument name="EmptyAsNull" default="" required="false">
<cfset var LOCAL = StructNew()>
<cfset LOCAL.Columns = ListToArray(ARGUMENTS.QueryOne.ColumnList)>
<cfset LOCAL.EmptyAsNull = 0>
<cfif isValid("boolean", ARGUMENTS.EmptyAsNull) AND ARGUMENTS.EmptyAsNull>
<cfset LOCAL.EmptyAsNull = 1>
</cfif>
<cfloop query="ARGUMENTS.QueryTwo">
<cfset QueryAddRow(ARGUMENTS.QueryOne)>
<cfloop ARRAY="#LOCAL.Columns#" index="LOCAL.ColumnName">
<cfif StructKeyExists(ARGUMENTS.QueryTwo, LOCAL.ColumnName) AND (NOT LOCAL.EmptyAsNull OR LEN(ARGUMENTS.QueryTwo[LOCAL.ColumnName][ARGUMENTS.QueryTwo.CurrentRow]))>
<cfset ARGUMENTS.QueryOne[LOCAL.ColumnName][ARGUMENTS.QueryOne.RecordCount] = ARGUMENTS.QueryTwo[LOCAL.ColumnName][ARGUMENTS.QueryTwo.CurrentRow]>
</cfif>
</cfloop>
</cfloop>
<cfreturn>
</cffunction>