dongtiao0279 2017-03-27 14:31
浏览 144
已采纳

INSERT INTO mysql时的唯一值

I have the following table in mysql:

    CREATE TABLE `kampbs` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user` varchar(20) COLLATE utf8_danish_ci DEFAULT NULL,
 `k1` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
 `k1r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
 `k2` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
 `k2r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
 `k3` varchar(1) COLLATE utf8_danish_ci DEFAULT NULL,
 `k3r` varchar(10) COLLATE utf8_danish_ci DEFAULT NULL,
 `week` int(2) DEFAULT NULL,
 `grp` varchar(11) COLLATE utf8_danish_ci DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_danish_ci

I have a form, that INSERT INTO the fields in the database, but it should only be possible to insert once a week pr user. So it should check if the column 'user' and 'week' are unique together. Make sense? :/

Let's say the user 'freak' submit in week 13, he shouldn't be able to submit once again in week 13.

I use the following $sql:

$sql = "INSERT INTO kampbs(user, k1, k1r, k2, k2r, k3, k3r, week, grp) VALUES('$username', '$k1', '$k1r', '$k2', '$k2r', '$k3', '$k3r', '$week', '$grp')";
  • 写回答

1条回答 默认 最新

  • dsfsdfsdfsdf6455 2017-03-27 14:33
    关注

    You can add a constraint to your table, so that the user / week couple is forced to be unique

    ALTER TABLE `kampbs` ADD UNIQUE `unique_index`(`user`, `week`);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 静电纺丝煅烧后如何得到柔性纤维
  • ¥15 (标签-react native|关键词-镜像源)
  • ¥100 照片生成3D人脸视频
  • ¥15 伪装视频时长问题修改MP4的时长问题,
  • ¥15 JETSON NANO
  • ¥15 VS开发qt时如何在paintgl函数中用pushbutton控制切换纹理
  • ¥20 关于 openpyxl 处理excel文件地问题
  • ¥15 MS中不知道高分子的构型怎么构建模型
  • ¥60 QQOP数据,什么是op数据号,怎么提取op数据!能不能大量提取(语言-c语言)
  • ¥15 matlab代码 关于微分方程和嵌套的分段函数。