0
CREATE TABLE `FOLLOWERS` 
(`FOLLOWER_ID` char(255) COLLATE utf8_unicode_ci NOT NULL, 
`FOLLOWING_ID` char(255) COLLATE utf8_unicode_ci NOT NULL, 
`FOLLOWING_IN` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

How can I prevent duplicate entries over multiple columns?

For example, I don't need anything like this

FOLLOWER_ID FOLLOWING_ID FOLLOWING_IN
283 283 ...
193 283 ...
908 908 ...
  • First row = Bad
  • Second = Good
  • Third = Bad

And I want to ask, Is the followers' table looks good design?

Wei291
  • 15
  • 8
  • Many people would expect an ID column to be numeric. The example data you share is consistent with that expectation. It's puzzling that you chose `char` as the type. – Jeff Holt May 27 '22 at 16:20
  • @JeffHolt Yes User Id is Char like this A34zwie29143, But above is example only – Wei291 May 27 '22 at 16:33
  • That looks like a user name, not a user id. Would you really want to modify more than one row if a user wanted to use another name? – Jeff Holt May 27 '22 at 16:37
  • I get user id from firebase auth – Wei291 May 27 '22 at 16:39

1 Answers1

2

If you're using MySQL 8.0.16 or newer, you can use a CHECK constraint.

CREATE TABLE `FOLLOWERS` (
    `FOLLOWER_ID` char(255) COLLATE utf8_unicode_ci NOT NULL, 
    `FOLLOWING_ID` char(255) COLLATE utf8_unicode_ci NOT NULL, 
    `FOLLOWING_IN` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT CHECK (FOLLOWER_ID != FOLLOWING_ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

If you're using an older version, see Can a MySQL trigger simulate a CHECK constraint? for how to emulate check constraints with triggers.

Barmar
  • 669,327
  • 51
  • 454
  • 560