简体   繁体   English

在SQL中保存数据的最佳做法

[英]Best practice for saving data in SQL

I am creating a survey. 我正在创建调查。 It is long enough that I want to give people a chance to save what they have so far. 我想给人们足够的时间来保存他们到目前为止所拥有的足够长的时间。 I am wondering what the best practice is for saving the data. 我想知道保存数据的最佳实践是什么。 Do I turn off foreign key constraints so if they haven't selected everything yet then foreign key constraint errors are ignored. 我是否关闭外键约束,所以如果它们还没有选择所有内容,那么外键约束错误将被忽略。 In this example I use an ID to link the documents table to the table that holds what they have selected. 在此示例中,我使用一个ID将文档表链接到保存他们所选内容的表。 If they haven't selected a document yet then a -1 is inserted as a holder. 如果他们还没有选择文档,则插入-1作为持有人。 Or do I create a second table to hold the saved place data. 还是创建第二个表来保存已保存的位置数据。 Or is there a third option. 还是有第三种选择。

There is a 3rd option. 有第三个选择。 You can generate the primary key right when the user begins the survey. 您可以在用户开始调查时生成主键权限。 There are two ways to do this: 有两种方法可以做到这一点:

  • Generate a database record and read-back the primary key (assumes it's generated by the database) 生成数据库记录并回读主键(假设它是由数据库生成的)
  • Change the primary key to be a GUID and simply generate a GUID in code. 将主键更改为GUID,然后简单地在代码中生成GUID。

OK, using -1 this way means that you have to have document in the documents table with an id of -1. 好的,以这种方式使用-1意味着您必须在文档表中拥有ID为-1的文档。 If you don't a better structure would be to define the field as allowing nulls. 如果没有更好的结构,则将字段定义为允许空值。 Then you pass in a null value. 然后,您传入一个空值。

You might want to read this: Can a foreign key be NULL and/or duplicate? 您可能需要阅读以下内容: 外键可以为NULL和/或重复吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM