我听说在编写SQL命令时使用SELECT *通常是不好的做法,因为选择您特别需要的列会更有效。
如果我需要选择表中的每一列,我应该使用
SELECT * FROM TABLE
or
SELECT column1, colum2, column3, etc. FROM TABLE
在这种情况下,效率真的重要吗?如果你真的需要所有的数据,我认为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').
当然,对于一个小而简单的系统来说,所有这些都不太重要。
当且仅当需要获取所有字段的数据时,使用显式字段名并不比使用*更快。
你的客户端软件不应该依赖于返回字段的顺序,所以这也是毫无意义的。
而且有可能(尽管不太可能)需要使用*获取所有字段,因为您还不知道存在哪些字段(考虑非常动态的数据库结构)。
使用显式字段名的另一个缺点是,如果字段名很多而且很长,那么阅读代码和/或查询日志就会更加困难。
所以规则应该是:如果你需要所有的字段,使用*,如果你只需要一个子集,显式命名它们。