Mysql中的两列在column1和column2之间具有唯一性约束
让我们考虑一个用户表: Username,email1,email2
现在,我想确保此表中没有两行具有任何共同的电子邮件地址。 确保这一点的最佳方法是什么?
例如:如果表中有行:“Bill,[电子邮件受保护],< a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae8e3e6e6caede7ebe3e6a4e9e5e7">[电子邮件受保护]",然后 尝试插入类似“Billy,[email protected],[email protected]" 应该会给出错误。
提前致谢, 钱德雷什
Let us consider a user table:
Username,email1,email2
Now, I want to make sure that no two rows in this table have any common email address. What would be the best way to ensure this ?
E.g.: If table has row: "Bill,[email protected],[email protected]", then
trying to insert a row like "Billy,[email protected],[email protected]" should give an error.
Thanks in advance,
Chandresh
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您正在尝试使用数据模型强制执行 1:1 和 1:multiple 之间的组合。 更好的选择是单独存储每个用户名/电子邮件组合。 一行代表“用户名,电子邮件1”,另一行代表“用户名,电子邮件2”。 如果您有其他与“用户名”相关的字段,这些字段可以保留在核心用户表中,而电子邮件将移动到两列电子邮件表,并在(用户名,电子邮件)上具有多列唯一索引。
It looks like you're trying to force a combo between 1:1 and 1:multiple with your data model. Your better bet is to store each Username/Email combo separately. One row for "Username,email1" and another row for "Username,email2". If you have additional "Username"-related fields, those could stay in the core User table, while emails would move to a two-column Email table with a multi-column unique index on (Username,Email).
遗憾的是,
check
约束并不是 MySQL 的一项功能。 嗯,确实如此,但他们被忽视了。使用
触发器
代替:Sadly,
check
constraints are not a feature of MySQL. Well, they are, but they're ignored.Use a
trigger
, instead:也许您可以使用某种存储过程,但这可能是您在插入数据之前可以检查的内容。
Maybe you could use some sort of stored procedure, but this may be something that you could check for before inserting your data.