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

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

SELECT * FROM TABLE

or

SELECT column1, colum2, column3, etc. FROM TABLE

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

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

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

然而,鉴于我所看到的反应,这似乎仍然是一个坏主意,由于我曾经考虑过的许多技术原因,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.

其他回答

总之,至少在PostgreSQL中,选择所有带*和不带*的列的性能几乎是一样的。

在PostgreSQL中,我创建了包含10个id_x列和1000万行的测试表,如下所示:

CREATE TABLE test AS SELECT generate_series(1, 10000000) AS id_1,
                            generate_series(1, 10000000) AS id_2,
                            generate_series(1, 10000000) AS id_3,
                            generate_series(1, 10000000) AS id_4,
                            generate_series(1, 10000000) AS id_5,
                            generate_series(1, 10000000) AS id_6,
                            generate_series(1, 10000000) AS id_7,
                            generate_series(1, 10000000) AS id_8,
                            generate_series(1, 10000000) AS id_9,
                            generate_series(1, 10000000) AS id_10;

然后,我交替运行以下2个查询共20次。*每个查询总共运行10次:

SELECT * FROM test:
SELECT id_1, id_2, id_3, id_4, id_5, id_6, id_7, id_8, id_9, id_10 FROM test;

结果> <

Select all columns with * Select all columns without *
1st run 12.792 seconds 12.483 seconds
2nd run 12.803 seconds 12.608 seconds
3rd run 12.537 seconds 12.549 seconds
4th run 12.512 seconds 12.457 seconds
5th run 12.570 seconds 12.487 seconds
6th run 12.508 seconds 12.493 seconds
7th run 12.432 seconds 12.475 seconds
8th run 12.532 seconds 12.489 seconds
9th run 12.532 seconds 12.452 seconds
10th run 12.437 seconds 12.477 seconds
Average 12.565 seconds 12.497 seconds

选择所有列的平均值:

*是12.565秒。 没有*是12.497秒。

使用特定的字段名,这样如果有人更改了您的表,您就不会得到意想不到的结果。关于主题:在执行插入操作时始终指定字段名,这样如果稍后需要添加列,就不必在生产版本中同时修复程序和更改数据库。

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

为应用程序中期望获得的每一列命名还可以确保如果有人更改表,只要您的列仍然存在(以任何顺序),应用程序就不会崩溃。

对于直接查询DB(例如通过sqlplus提示符或通过DB管理工具),选择*通常很好——它省去了写出所有列的麻烦。

另一方面,在应用程序代码中最好枚举列。这有几个好处:

代码更清晰 你将知道结果返回的顺序(这对你来说可能重要,也可能不重要)