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 R语言爬虫的时候元素和园代码不一样怎么解决呀
  • ¥15 VS2022多项目启动有问题
  • ¥15 SQL删除添加数据后序号不连续问题。
  • ¥15 首次运行OmniEvent运行报错
  • ¥15 有没有人知道这个问题怎么解决
  • ¥15 comsol电力电缆载流量仿真
  • ¥15 webSocket可以接TCP socket接口吗
  • ¥60 mpi并行出错,CFD++计算
  • ¥15 c#:vsto,powerpoint的外接程序中换主题颜色
  • ¥15 状态机/汽车转向灯/Sateflow