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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

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

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

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

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

其他回答

在性能方面,具有特定列的SELECT可以更快(不需要读入所有数据)。如果您的查询确实使用了所有列,那么带显式参数的SELECT仍然是首选。任何速度差异基本上都是不明显的,并且接近恒定时间。总有一天你的模式会改变,这是预防由此产生问题的好保险。

效率是否重要很大程度上取决于生产数据集的大小(以及它们的增长率)。如果您的数据集没有那么大,也没有那么快地增长,那么选择单个列可能没有太大的性能优势。

随着数据集越来越大,数据增长速度越来越快,性能优势变得越来越重要。

为了以图形方式查看是否有任何不同,我建议使用查询分析器查看SELECT *和等效的SELECT col1、col2等的查询执行计划。这将告诉您两个查询中哪一个更有效。您还可以生成一些不同体积的测试数据,看看时间是什么。

select *是一件坏事,有四个主要原因:

The most significant practical reason is that it forces the user to magically know the order in which columns will be returned. It's better to be explicit, which also protects you against the table changing, which segues nicely into... If a column name you're using changes, it's better to catch it early (at the point of the SQL call) rather than when you're trying to use the column that no longer exists (or has had its name changed, etc.) Listing the column names makes your code far more self-documented, and so probably more readable. If you're transferring over a network (or even if you aren't), columns you don't need are just waste.

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

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

记住,如果根据定义有一个内部连接,则不需要所有列,因为连接列中的数据是重复的。

It's not like listing columns in SQl server is hard or even time-consuming. You just drag them over from the object browser (you can get all in one go by dragging from the word columns). To put a permanent performance hit on your system (becasue this can reduce the use of indexes and becasue sending unneeded data over the network is costly) and make it more likely that you will have unexpected problems as the database changes (sometimes columns get added that you do not want the user to see for instance) just to save less than a minute of development time is short-sighted and unprofessional.