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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

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.

其他回答

每次都定义你想要SELECT的列。没有理由不这样做,性能的提高是非常值得的。

他们不应该给“SELECT *”选项

这取决于您的DB服务器的版本,但现代版本的SQL可以以任何一种方式缓存该计划。我想说的是,不管你的数据访问代码有什么可维护性,你都要使用它。

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.

您实际上应该只选择您需要的字段,并且只选择所需的数量,即。

SELECT Field1, Field2 FROM SomeTable WHERE --(constraints)

在数据库之外,动态查询有注入攻击和畸形数据的风险。通常使用存储过程或参数化查询来解决这个问题。而且(虽然不是真正的大问题)服务器必须在每次执行动态查询时生成一个执行计划。

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