为什么SELECT *是不好的做法?如果您添加了想要的新列,这难道不意味着需要更改的代码更少吗?
我知道SELECT COUNT(*)在某些db上是一个性能问题,但是如果您真的想要每个列呢?
为什么SELECT *是不好的做法?如果您添加了想要的新列,这难道不意味着需要更改的代码更少吗?
我知道SELECT COUNT(*)在某些db上是一个性能问题,但是如果您真的想要每个列呢?
当前回答
SELECT语句中的星号“*”是查询中涉及的表中所有列的简写。
性能
简写可能会慢一些,因为:
并不是所有的字段都被索引,这迫使对整个表进行扫描——效率较低 保存到通过线路发送SELECT *的内容可能会导致全表扫描 返回比需要的更多的数据 使用可变长度数据类型返回尾随列会导致搜索开销
维护
当使用SELECT *时:
Someone unfamiliar with the codebase would be forced to consult documentation to know what columns are being returned before being able to make competent changes. Making code more readable, minimizing the ambiguity and work necessary for people unfamiliar with the code saves more time and effort in the long run. If code depends on column order, SELECT * will hide an error waiting to happen if a table had its column order changed. Even if you need every column at the time the query is written, that might not be the case in the future the usage complicates profiling
设计
SELECT *是一个反模式:
查询的目的不那么明显;应用程序使用的列是不透明的 它打破了尽可能使用严格类型的模块化规则。Explicit几乎在所有情况下都更好。
什么时候应该使用“SELECT *”?
如果显式地需要涉及表中的每一列,而不是编写查询时存在的每一列,则使用SELECT *是可以接受的。数据库将在内部将*展开为完整的列列表—没有性能差异。
否则,显式地列出要在查询中使用的每一列—最好是在使用表别名时。
其他回答
我不认为这真的可以有一个通用的规则。在许多情况下,我避免使用SELECT *,但我也使用过SELECT *非常有用的数据框架。
和所有事情一样,有收益也有成本。我认为收益与成本的等式的一部分是你对数据结构有多少控制。在SELECT *工作良好的情况下,数据结构受到严格控制(它是零售软件),因此没有太大的风险,有人会将一个巨大的BLOB字段发送到表中。
使用列名进行选择提高了数据库引擎从索引访问数据的可能性,而不是查询表数据。
当数据库模式发生变化时,SELECT *使您的系统暴露在意想不到的性能和功能变化中,因为您要将任何新列添加到表中,即使您的代码还没有准备好使用或显示这些新数据。
If you name the columns in a SELECT statement, they will be returned in the order specified, and may thus safely be referenced by numerical index. If you use "SELECT *", you may end up receiving the columns in arbitrary sequence, and thus can only safely use the columns by name. Unless you know in advance what you'll be wanting to do with any new column that gets added to the database, the most probable correct action is to ignore it. If you're going to be ignoring any new columns that get added to the database, there is no benefit whatsoever to retrieving them.
引用自这篇文章。
永远不要用“SELECT *”,
我发现使用“SELECT *”的原因只有一个。
如有特殊要求和创建动态环境时添加或删除列,由应用程序代码自动处理。在这种特殊情况下,您不需要更改应用程序和数据库代码,这将自动影响生产环境。在这种情况下,您可以使用“SELECT *”。
如果您真的想要每个列,我没有看到select(*)和命名列之间的性能差异。命名列的驱动程序可能只是为了明确您希望在代码中看到哪些列。
但是,通常情况下,您不希望每个列和select(*)会导致数据库服务器做不必要的工作,并且必须通过网络传递不必要的信息。它不太可能造成明显的问题,除非系统被大量使用或网络连接很慢。