MySQL:使列唯一?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6567500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL: making a column unique?
提问by StackOverflowNewbie
I have a table that is in production. I realize that some of the columns should be unique. Is it safe to go into phpMyAdmin and change those columns to make it unique?
我有一张正在生产的桌子。我意识到某些列应该是独一无二的。进入 phpMyAdmin 并更改这些列以使其独一无二是否安全?
ALTER TABLE `foo` ADD UNIQUE ( `bar` )
采纳答案by Itay Moav -Malimovka
- You do not have duplicates -> will apply the key without issues
- You do have duplicates -> will give an error message, nothing happened to your data
- All is unique, except several rows with NULL in them, unique constraint is still applied, as NULL is not checked when checking for unique values (you can have the entire table have a NULL value in a unique field without any error message).
- 您没有重复项 -> 将应用密钥而不会出现问题
- 您确实有重复项 -> 将给出错误消息,您的数据没有任何变化
- 所有都是唯一的,除了其中有 NULL 的几行之外,仍然应用唯一约束,因为在检查唯一值时不检查 NULL(您可以让整个表在唯一字段中具有 NULL 值而没有任何错误消息)。
One more thing, if you have a prod DB, you must also have a dev DB which you can test on without fear, right?
还有一件事,如果你有一个生产数据库,你也必须有一个开发数据库,你可以无所畏惧地对其进行测试,对吧?
回答by Rahul Mankar
Follow the below steps to apply unique column value from phpmyadmin panel:
按照以下步骤从 phpmyadmin 面板应用唯一的列值:
Go to the table structure. Click on the unique keyword as like below -
转到表结构。单击如下所示的唯一关键字 -
Click on the ok from confirmation box -
单击确认框中的确定 -
Unique value constraint for column will apply. Or you can run mysql query:
将应用列的唯一值约束。或者你可以运行 mysql 查询:
ALTER TABLE user ADD UNIQUE(email);
ALTER TABLE user ADD UNIQUE(email);
回答by Eoin
I had this problem and my values were not unique. I also couldn't find an easy way to edit this problem in PHPMyAdmin. Here's how I solved it:
我有这个问题,我的价值观不是唯一的。我也找不到在 PHPMyAdmin 中编辑此问题的简单方法。这是我解决它的方法:
I clicked into the table I needed to update
I exported the table, changing it to be a CSV export and then edited it manually to update the non-unique values.
- Making sure I was still in the table I had exported (because I wanted to keep the headers intact), I imported my newly saved CSV
我点击了我需要更新的表格
我导出了表格,将其更改为 CSV 导出,然后手动编辑它以更新非唯一值。
- 确保我仍在导出的表格中(因为我想保持标题完整),我导入了我新保存的 CSV
Hope that saves someone some time in the future.
希望在未来可以节省一些时间。
回答by Oscar Gomez
It will only be a problem if the pre-existing values on the table are not unique, otherwise I don't think there will be any problem.
只有表上预先存在的值不是唯一的才会有问题,否则我认为不会有任何问题。
回答by MD Sayem Ahmed
If there are already some duplicate values in those columns, then this will generate an error. If there aren't any duplicate values in those columns, then you will be fine.
如果这些列中已经有一些重复的值,那么这将产生一个错误。如果这些列中没有任何重复值,那么您会没事的。