在查询的查询中使用通配符运算符

Using a wildcard operator in a query of query

我有以下代码:

<cfquery name="somequery1" datasource="somedsn">
    SELECT somecolumn1, somecolumn2, somecolumn3 
    FROM sometable 
    WHERE someid = <cfqueryparam cfsqltype="cf_sql_integer" value="1">
</cfquery>

<cfquery name="somequery2" dbtype="query">
    SELECT *
    FROM somequery1
</cfquery>

我的代码管理员说我需要将查询的查询更改为:

<cfquery name="somequery2" dbtype="query">
    SELECT somecolumn1, somecolumn2, somecolumn3 
    FROM somequery1
</cfquery>

谁能解释一下为什么我需要在 Query of Query 中重新定义列引用?当然,通配符运算符会处理这个问题。

重新定义 Coldfusion Query of Queries 的 SELECT 子句中的列引用是否有任何技术或性能提升?这假设列引用已经在提供给查询的查询的数据库查询中明确设置。

我相信通配符的使用使代码更清晰,更易于更新,因为对列引用的任何更改只需要进行一次。

编辑:

正如所讨论的,是的,考虑到它会包含任何更改(例如,如果您需要在 selected 列中进行更改)这一事实,您当前的代码将更加模块化是正确的您的查询,即,它将处理您将来可能添加的任何列。所以你现在的查询是有效的,可以继续进行。


如果您想 select 所有列,通配符肯定会处理它,但是现在不推荐并且通常不喜欢在 selecting 列时使用通配符。你可以看看 Aaron Bertrand Bad habits to kick : using SELECT * / omitting the column list:

But there are several reasons why you should avoid SELECT * in production code:

  1. You can be returning unnecessary data that will just be ignored, since you don't usually need every single column. This is wasteful in I/O, since you will be reading all of that data off of the pages, when perhaps you only needed to read the data from the index pages. It is also wasteful in network traffic and in many cases the memory required by the consuming application to hold the results.
  2. When you use SELECT * in a join, you can introduce complications when multiple tables have columns with the same name (not only on the joined columns, such as OrderID, which are typically the same, but also peripheral columns like CreatedDate or Status). On a straight query this might be okay, but when you try to order by one of these columns, or use the query in a CTE or derived table, you will need to make adjustments.
  3. While applications should not be relying on ordinal position of columns in the resultset, using SELECT * will ensure that when you add columns or change column order in the table, the shape of the resultset should change. Ideally, this should only happen intentionally.

正如您与 Rahul 讨论的那样:如果这是基于数据库的查询,您的 "code manager" 提供了很好的建议,但我认为它在 CFML 查询时查询的上下文中有点过分.

我怀疑他们已经听过有关数据库查询的指南,但在提供有关内存查询操作的指南时并没有真正充分考虑。

简而言之:您的代码比他们建议的更改更优化。

这是另一种方法。

<cfset selectFields = "somecolumn1, somecolumn2, somecolumn3">

<cfquery name="somequery1" datasource="somedsn">
select #selectFields#
etc
</cfquery>

<cfquery name="somequery2" dbtype="query">
select #selectFields#
from somequery1
</cfquery>

您可以明智地利用自己的时间,您的代码经理可能真的会喜欢它。