在用编程语言编写 SQL 时,使用自然连接或隐式列名不是一个好习惯吗?
当我们使用自然连接时,当两个表具有相同的列名时,我们就会连接表。但是,如果我们用 PHP 编写它,然后 DBA 向两个表添加更多字段,那么自然连接可能会中断,该怎么办?
对于插入也是如此,如果我们这样做,
insert into gifts values (NULL, "chocolate", "choco.jpg", now());
那么当 DBA 向表中添加一些字段(例如第 2 或第 3 列)时,它会破坏代码并污染表。因此,当 SQL 语句是用编程语言编写并存储在大型项目的文件中时,最好总是拼写出列名称。
When we use Natural Join, we are joining the tables when both table have the same column names. But what if we write it in PHP and then the DBA add some more fields to both tables, then the Natural Join can break?
The same goes for Insert, if we do a
insert into gifts values (NULL, "chocolate", "choco.jpg", now());
then it will break the code as well as contaminating the table when the DBA adds some fields to the table (example as column 2 or 3). So it is always best to spell out the column names when the SQL statements are written inside a programming language and stored in a file in a big project.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无论您在何处编写自然连接,都不是一个好主意。它们隐藏了更明确的代码会暴露的含义,并且如果列名称发生更改,可能会引入微妙的错误。
Natural joins are not a good idea wherever you write them. They hide the meaning that more explicit code would expose and may introduce subtle bugs if column names change.
是的,明确命名您关心的列总是一个好主意。正如您所指出的,如果有人向表中添加列,这可以防止查询中断。
这同样适用于更喜欢在 SELECT 中列出列而不是编写
SELECT *
。请参阅此相关问题。Yes it is always a good idea to explicitly name the columns you are concerned with. As you point out, this prevents the query breaking if someone adds a column to the table.
The same applies for prefering to list columns in a SELECT instead of writing
SELECT *
. See this related question.是的,明确说明您的字段始终是最佳实践。否则,当您修改架构时,您的代码将会中断。
yes it is always best practice to state your fields explicitly. Otherwise when you modify your schema, your code will break.