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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

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


当前回答

上面所有人说的,加上:

如果你正在努力编写可读性强、可维护的代码,可以这样做:

SELECT foo, bar FROM widgets;

立即可读并显示意图。如果你打了那个电话,你知道你会得到什么。如果widget只有foo和bar列,那么选择*意味着您仍然需要考虑返回什么,确认顺序映射正确等等。然而,如果widget有更多的列,但您只对foo和bar感兴趣,那么当您查询通配符,然后只使用返回的部分内容时,您的代码就会变得混乱。

其他回答

明确地定义列,因为SQL Server将不需要对列进行查找来拉出它们。如果定义了列,则SQL可以跳过该步骤。

在某些情况下,SELECT *适用于维护目的,但一般情况下应该避免使用。

These are special cases like views or stored procedures where you want changes in underlying tables to propagate without needing to go and change every view and stored proc which uses the table. Even then, this can cause problems itself, like in the case where you have two views which are joined. One underlying table changes and now the view is ambiguous because both tables have a column with the same name. (Note this can happen any time you don't qualify all your columns with table prefixes). Even with prefixes, if you have a construct like:

选择A., B. -您可能会遇到客户端现在难以选择正确字段的问题。

一般来说,我不使用SELECT *,除非我在做一个有意识的设计决策,并指望相关的风险很低。

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.

在执行效率方面,我不知道有什么显著差异。但是为了程序员的效率,我会写字段名,因为

如果您需要按数字进行索引,或者您的驱动程序对blob-values的行为很奇怪,那么您需要一个明确的顺序 如果需要添加更多字段,则只读取所需的字段 如果拼写错误或重命名字段,而不是记录集/行中的空值,则会得到sql-error 你可以更好地了解发生了什么。

指定列列表通常是最好的选择,因为如果有人向表中添加/插入列,您的应用程序不会受到影响。