应用程序开发人员常见的数据库开发错误有哪些?


当前回答

我想补充一点: 偏好“优雅”代码而不是高性能代码。在应用程序开发人员看来,对数据库最有效的代码通常是丑陋的。

Believing that nonsense about premature optimization. Databases must consider performance in the original design and in any subsequent development. Performance is 50% of database design (40% is data integrity and the last 10% is security) in my opinion. Databases which are not built from the bottom up to perform will perform badly once real users and real traffic are placed against the database. Premature optimization doesn't mean no optimization! It doesn't mean you should write code that will almost always perform badly because you find it easier (cursors for example which should never be allowed in a production database unless all else has failed). It means you don't need to look at squeezing out that last little bit of performance until you need to. A lot is known about what will perform better on databases, to ignore this in design and development is short-sighted at best.

其他回答

使用一些疯狂的构造和应用逻辑,而不是简单的COALESCE。

忘记在表之间建立关系。我记得当我刚开始在我现在的雇主工作时,我不得不清理这些东西。

当查询在您的开发机器上运行得如此之快时,一旦您向应用程序抛出一些流量,查询就会崩溃并阻塞,这要归咎于db引擎。

我讨厌开发人员使用嵌套的选择语句,甚至在查询的“select”部分中返回选择语句的结果的函数。

我很惊讶我在其他地方没有看到这个,也许我忽略了它,尽管@adam也有类似的问题。

例子:

SELECT
    (SELECT TOP 1 SomeValue FROM SomeTable WHERE SomeDate = c.Date ORDER BY SomeValue desc) As FirstVal
    ,(SELECT OtherValue FROM SomeOtherTable WHERE SomeOtherCriteria = c.Criteria) As SecondVal
FROM
    MyTable c

在这个场景中,如果MyTable返回10000行,结果就好像查询只运行了20001个查询,因为它必须运行初始查询,并对每一行结果查询一次其他表。

开发人员可以在只返回几行数据且子表通常只有少量数据的开发环境中使用这种查询,但在生产环境中,随着向表中添加更多数据,这种查询的成本可能会呈指数级增长。

一个更好的(不一定完美的)例子是这样的:

SELECT
     s.SomeValue As FirstVal
    ,o.OtherValue As SecondVal
FROM
    MyTable c
    LEFT JOIN (
        SELECT SomeDate, MAX(SomeValue) as SomeValue
        FROM SomeTable 
        GROUP BY SomeDate
     ) s ON c.Date = s.SomeDate
    LEFT JOIN SomeOtherTable o ON c.Criteria = o.SomeOtherCriteria

这允许数据库优化器将数据混合在一起,而不是从主表中重新查询每条记录,我通常发现,当我必须修复产生这个问题的代码时,我通常会将查询速度提高100%或更多,同时减少CPU和内存使用。

二十年来我见过的最常见的错误是:没有提前计划。许多开发人员将创建数据库和表,然后在构建应用程序时不断修改和扩展表。最终的结果往往是一团糟,效率低下,之后很难清理或简化。