简体   繁体   中英

MySQL disallow row that has 2 identical column values with another row

This is my MySQL table:

在此处输入图片说明

  • The left column auto increments.
  • The center column is the id# of the user.
  • The right column is the id# of a post that they like.

I am inserting data into the table like so:

$stmt = $db->prepare("INSERT INTO likes (user_id,post_id) VALUES (?,?)");
$stmt->execute(array($_SESSION['user'],$_POST['id']));

This works fine, but as you can see the MySQL table has two identical rows (id's 3 & 4) which both have a user_id of 5 and a post_id of 196. In other words my MySQL table records that the user with id = 5 likes the post with id = 196 two times. how do I disallow a situation where there are two rows that have identical user_id's and identical post_id's

您需要在user_id和post_id列上设置唯一约束

Update

The below answer could result in Race Conditions and possibly duplicate database entries in some cases.

Thanks to @Martin for finding the major flaws in the below system:


This is something you should do in business logic. The way I have implemented an almost identical system is this (in psuedo-code):

Show Blog/Video/Post/Etc.

Has user "liked" this?
    Yes = show "unlike" button (on server, not JS)
    No  = show "like" button (on server, not JS)

Add or delete "like" as necessary

The code to show either button is on the server, so the user can't intercept it and manually pick which one to do.

The only flaw is that there has to be a way to identify which button the user clicks, which means the user could spend a lot of time digging and fiddling and possibly change the button/link/whatever on the page.

I overcome this by testing on the server for whether the user has already liked or not, and then inserting only when they have NOT.

CREATE UNIQUE INDEX user_post on likes (user_id, post_id)

这样可以防止相同(user_id,post_id)值超过一次...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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