Should one generate a unique id for each row in a database table that otherwise has no unique keys?

て烟熏妆下的殇ゞ 提交于 2019-12-12 03:22:04

问题


I'm designing a MySQL database for a startup working with patient medical records. I have several tables that can have no unique keys: medical conditions, allergies, family history, etc. For example the medications table might have fields patient_id, med_name, usage_dates, dosage, reason, etc. The only guaranteed unique key is all of the fields together.

A web application can easily retrieve this data for a given patient by selecting for patient_id, but unless it is possible to save pointers to rows inside a database with multiple users, it strikes me as a clumsy system for editing or deleting rows in this table. The DBMS would have to select for each field's value in order to find the correct row. From what (little) I know about databases, I imagine this could be inefficient in a large database.

Would it be more efficient to create a new field with an ID number to function as a primary key in each of these tables, or is the DBMS way smarter than me and this is totally unnecessary?


回答1:


You can always add a simple numeric primary key (e.g. mysql auto_increment) so you DO end up with a unique identifier for each row. Composite primary keys are a serious pain if you have to use the table in a foreign key relationship, forcing you to list each of the primary key's component's field's in all joins/FK specifications. By comparison, adding a simple int primary key reduces you to carrying that ONE field around for the FK/join relationships.

I'd suggest something along the lines of:

patients (id, name, ....)
meds (id, brand, name, ...)
patient_meds (patient_id, med_id, dosage, ...)



回答2:


Yes, this would be called a "synthetic key", and I would certainly add one, probably as just an AUTO_INCREMENT field. It will make updates a lot simpler (and faster) if you do.




回答3:


I think an ID field is almost always a good idea. It guarantees one column that you can use to uniquely identify one row in your database. I also think it's a good idea because it can make your queries faster because the primary key of a table is indexed, so if you select based on the unique ID column, MySQL doesn't have to search through all the rows to find the one you're looking for. It knows exactly where to go and you queries will run much faster.




回答4:


Yes, it is a "best practice". In addition to updates, it makes deletes and certain joins much faster.

Many third party tools depend on a unique primary key.



来源:https://stackoverflow.com/questions/8852758/should-one-generate-a-unique-id-for-each-row-in-a-database-table-that-otherwise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!