There's situation when I have table named "status", which only contains ID (PK) and name (string, unique). Also, other table has reference to this status (e.g. 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). 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?
NOTES: this is also general programming question (no direct SQL queries). I was not able to find a tag for it.
If
nameis a column including unique values, you can usenamefield to get theIDand then use theID. However, Usually thenamecolumn does not include unique values, so it is required to use other columns to receive only 1 id instead of multiple.See the situation:
Here, if you use
namefield, you will get 2 differentIDsreturned which will cause an error. That's why you'll need another approach like:to make sure one unique id is being returned.
To sum up, if you are sure the
namefield includes unique values, use the field to get theIDinstead of using theIDvalue hardcoded. 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.