简体   繁体   English

创建没有主键的MySQL表

[英]Create MySQL table without Primary Key

I have a table that does not require a primary key. 我有一个不需要主键的表。 It consists of 4 columns which are email,date,time,message. 它由4列组成,分别是电子邮件,日期,时间,消息。 Each time a user logs in, logs out, or does any particular action that is important, I log the email, date, time and action (message). 每次用户登录,注销或执行任何重要的特定操作时,我都会记录电子邮件,日期,时间和操作(消息)。 Currently the table is setup with email as the Primary Key but I am unable to insert more than one record with the same email. 目前,该表已使用电子邮件作为主键进行设置,但我无法在同一电子邮件中插入多个记录。 I suppose I could use time as the PK but there is the possibility that two actions fall on the same time. 我想我可以将时间用作PK,但是有可能两个动作同时出现。 How can I just use the table without a PK? 我如何不使用PK就使用桌子? I have tried turning it off for the email column but it does not allow me to. 我尝试将其关闭以用于“电子邮件”列,但它不允许我这样做。

Yes as you have defined email field as your primary, it can hold unique data only and no duplication allowed. 是,因为您已将电子邮件字段定义为主要字段,所以它只能保存唯一数据,并且不允许重复。

So you have two options: 因此,您有两种选择:

1: Remove email field as a primary key 1:删除电子邮件字段作为主键

2: Add new integer field as a Primary key with auto increment (I would prefer this one) 2:将新的整数字段添加为具有自动增量的主键(我希望使用此整数)

You could use a natural primary key that would be a combination of Email + Date + Time + Action. 您可以使用自然主键 ,该主键可以是电子邮件+日期+时间+操作的组合。 That combination would be unique. 这种组合将是独特的。 It is impossible for the same user to do 2 different actions at the same time. 同一用户不可能同时执行2个不同的操作。 That will help you to keep integrity of your information. 这将帮助您保持信息的完整性。

Hope this helps you. 希望这对您有所帮助。

To make a decision on a table' primary key one may start with considering these points (applicable to innodb): 要决定一个表的主键,首先要考虑以下几点(适用于innodb):

  1. How the data is going to be accessed after it is written (if you don't query it, why store it?). 数据在写入后将如何访问(如果不查询,为什么要存储它?)。 If you care about read performance you should query your data by the primary key, since for innodb primary key is the only possible clustered index. 如果您关心读取性能,则应按主键查询数据,因为对于innodb,主键是唯一可能的聚集索引。

  2. The data is stored ordered by the primary key, so if you care about write performance, you should write data ideally ordered by your primary key, which always happens automatically if you have an auto_increment. 数据是按主键排序存储的,因此,如果您关心写性能,则应按主键写入理想排序的数据,如果您具有auto_increment,则该数据总是自动发生的。 Also table for which you don't explicitly specify a primary key are going to have a hidden auto_increment field which you won't be able to access, ie you get less for the same cost. 另外,您未明确为其指定主键的表将具有一个隐藏的auto_increment字段,您将无法访问该字段,即,以相同的成本获得的收益更少。

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

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