简体   繁体   English

硬编码ID与查询

[英]hardcoded ID vs query

There's situation when I have table named "status", which only contains ID (PK) and name (string, unique). 有一种情况,当我有一个名为“ status”的表时,该表仅包含ID(PK)和名称(字符串,唯一)。 Also, other table has reference to this status (eg status_id) 另外,其他表也引用了此状态(例如status_id)

let's say, there's two statuses: 假设有两种状态:

1 - status1
2 - status2

Now, I'd like to insert/update record in table2 (which has reference to status table). 现在,我想在table2中插入/更新记录(已引用状态表)。 What is the best way to do it, should I hardcode ID of status that I'd like to set or should I query by name, then get ID and assign it after? 最好的方法是什么,我应该对要设置的状态ID进行硬编码还是应该按名称查询,然后获取ID并在之后进行分配?

NOTES: this is also general programming question (no direct SQL queries). 注意:这也是一般的编程问题(无直接SQL查询)。 I was not able to find a tag for it. 我找不到它的标签。

If name is a column including unique values, you can use name field to get the ID and then use the ID . 如果name是包含唯一值的列,则可以使用name字段获取ID ,然后使用ID However, Usually the name column does not include unique values, so it is required to use other columns to receive only 1 id instead of multiple. 但是,通常name列不包含唯一值,因此需要使用其他列仅接收1个id而不是多个id。

See the situation: 查看情况:

ID name
1  John White
2  John White

Here, if you use name field, you will get 2 different IDs returned which will cause an error. 在这里,如果您使用name字段,您将获得2个不同的IDs ,这将导致错误。 That's why you'll need another approach like: 这就是为什么您需要另一种方法,例如:

..
where name = @name and dateOfBirth = @dob and MothersName=@mothersname

to make sure one unique id is being returned. 确保返回一个唯一的ID。

To sum up, if you are sure the name field includes unique values, use the field to get the ID instead of using the ID value hardcoded. 总之,如果您确定name字段包含唯一值,请使用该字段获取ID而不要使用经过硬编码的ID值。 Otherwise, you can try to create a key in the config file like "lookupid" and use its value instead of using the ID hardcoded still, will be better to maintain for the future. 否则,您可以尝试在配置文件中创建一个密钥,例如“ lookupid”,并使用其值而不是使用仍经过硬编码的ID,这样将来会更好。

Name isnt the best choice to check whats the id its the opposite because name at most of the times (can be same general case) would result into duplicates leading to redundancy of rows as you proceed with adding new columns as well making it worst. 名称不是检查id是什么的最佳选择,因为名称在大多数情况下(可能是相同的一般情况)会导致重复,从而导致行的冗余,因为您继续添加新列并使其更糟。 better choice as always is the primary key of the table or unique column you can have a unique constraint on your column to deal with duplicates in case you want it to be used as for a search for an id 与往常一样,更好的选择是表或唯一列的主键,如果希望将其用作搜索ID的对象,则可以对列进行唯一约束以处理重复项

Hardcoding is never a good idea but depends on how often the value changes throughout the life of code...using the query is better 硬编码永远不是一个好主意,而是取决于在整个代码生命周期中值多久更改一次……使用查询效果更好

sql SQL

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

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