我听说在编写SQL命令时使用SELECT *通常是不好的做法,因为选择您特别需要的列会更有效。

如果我需要选择表中的每一列,我应该使用

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

在这种情况下,效率真的重要吗?如果你真的需要所有的数据,我认为SELECT *在内部会更优,但我这么说并没有真正理解数据库。

我很好奇在这种情况下最好的做法是什么。

更新:我可能应该指定,我真正想要执行SELECT *的唯一情况是,当我从一个表中选择数据时,我知道总是需要检索所有列,即使添加了新列。

然而,鉴于我所看到的反应,这似乎仍然是一个坏主意,由于我曾经考虑过的许多技术原因,SELECT *不应该被使用。


当前回答

这将会被猛烈抨击,但我做了一个选择*,因为几乎所有的数据都是从SQL Server视图中检索的,这些视图将多个表中所需的值预组合到一个易于访问的视图中。

然后我想要所有的列从视图不会改变,当新字段添加到底层表。这有一个额外的好处,允许我改变数据的来源。视图中的FieldA一次可以被计算,然后我可以将其更改为静态。不管怎样,视图给我提供了FieldA。

它的美妙之处在于它允许我的数据层获得数据集。然后它将它们传递给我的BL,然后可以从它们创建对象。我的主应用程序只知道这些对象并与之交互。我甚至允许我的对象在传递数据箭头时自我创建。

当然,我是唯一的开发人员,所以这也有帮助:)

其他回答

The SELECT * might be ok if you actually needed all of the columns - but you should still list them all individually. You certainly shouldn't be selecting all rows from a table - even if the app & DB are on the same server or network. Transferring all of the rows will take time, especially as the number of rows grows. You should have at least a where clause filtering the results, and/or page the results to only select the subset of rows that need to be displayed. Several ORM tools exist depending on app language you are using to assist in querying and paging the subset of data you need. For example, in .NET Linq to SQL, Entity Framework, and nHibernate all will help you with this.

为应用程序中期望获得的每一列命名还可以确保如果有人更改表,只要您的列仍然存在(以任何顺序),应用程序就不会崩溃。

在执行效率方面,我不知道有什么显著差异。但是为了程序员的效率,我会写字段名,因为

如果您需要按数字进行索引,或者您的驱动程序对blob-values的行为很奇怪,那么您需要一个明确的顺序 如果需要添加更多字段,则只读取所需的字段 如果拼写错误或重命名字段,而不是记录集/行中的空值,则会得到sql-error 你可以更好地了解发生了什么。

当您有一个连接时,不使用select *对于性能特别重要,因为根据定义,至少两个字段包含相同的数据。您不希望将不需要的数据从数据库服务器发送到应用程序或web服务器而浪费网络资源。使用select *似乎更简单,但这是一种糟糕的做法。由于很容易将列名拖到查询中,所以只需这样做即可。

Another issue that occurs when using select * is that there are idiots who choose to add new fields in the middle fo the table (always a bad practice), if you use select * as the basis for an insert then suddenly your column order may be wrong and you may try to insert the social security number into the honorarium (the amoutn of money a speaker may get paid to pick a non-random example) which could be a very bad thing for data integrity. Even if the select isn't an insert, it looks bad to the customer when the data is suddenly in the worng order on the report or web page.

我认为在任何情况下使用select *都不会比使用列列表更好。您可能认为这样更容易维护,但事实并非如此,而且当您不需要的字段被添加到表中时,会导致您的应用程序毫无理由地变慢。您还必须面对修复问题,如果您使用列列表就不会损坏,因此您节省的不添加列的时间将用于此操作。

指定列列表通常是最好的选择,因为如果有人向表中添加/插入列,您的应用程序不会受到影响。