我听说在编写SQL命令时使用SELECT *通常是不好的做法,因为选择您特别需要的列会更有效。
如果我需要选择表中的每一列,我应该使用
SELECT * FROM TABLE
or
SELECT column1, colum2, column3, etc. FROM TABLE
在这种情况下,效率真的重要吗?如果你真的需要所有的数据,我认为SELECT *在内部会更优,但我这么说并没有真正理解数据库。
我很好奇在这种情况下最好的做法是什么。
更新:我可能应该指定,我真正想要执行SELECT *的唯一情况是,当我从一个表中选择数据时,我知道总是需要检索所有列,即使添加了新列。
然而,鉴于我所看到的反应,这似乎仍然是一个坏主意,由于我曾经考虑过的许多技术原因,SELECT *不应该被使用。
“select *”的问题在于可能会带来您并不真正需要的数据。在实际的数据库查询期间,所选列并不会真正增加计算量。真正“繁重”的是将数据传输回客户端,任何您并不真正需要的列都只会浪费网络带宽,并增加等待查询返回的时间。
即使您确实使用了来自“select *…”的所有列,这也只是暂时的。如果将来您更改表/视图布局并添加更多列,您将开始在您的选择中引入这些列,即使您不需要它们。
“select *”语句不好的另一个地方是视图创建。如果您使用“select *”创建了一个视图,然后向表中添加列,则视图定义和返回的数据将不匹配,您需要重新编译视图以使它们再次工作。
我知道写一个“选择*”是诱人的,因为我真的不喜欢手动指定所有的字段在我的查询,但当你的系统开始发展,你会发现这是值得花额外的时间/精力在指定字段,而不是花更多的时间和精力消除错误在你的视图或优化你的应用程序。
即使查询不是通过网络发送,SELECT *也是一种糟糕的做法。
Selecting more data than you need makes the query less efficient - the server has to read and transfer extra data, so it takes time and creates unnecessary load on the system (not only the network, as others mentioned, but also disk, CPU etc.). Additionally, the server is unable to optimize the query as well as it might (for example, use covering index for the query).
After some time your table structure might change, so SELECT * will return a different set of columns. So, your application might get a dataset of unexpected structure and break somewhere downstream. Explicitly stating the columns guarantees that you either get a dataset of known structure, or get a clear error on the database level (like 'column not found').
当然,对于一个小而简单的系统来说,所有这些都不太重要。