Home  >  Q&A  >  body text

Regardless of row, is the only column

<p>Is there a way to make the entire row unique regardless of the value in the column? </p> <p>So, if column <code>a</code> has <code>1</code>, column <code>b</code> has <code>2</code> , then if you insert <code>2</code> into column <code>a</code>, insert <code>1</code> into column <code>b</code> , an error will be thrown. </p> <pre class="brush:none;toolbar:false;"> --- --- | a | b | --- --- | 1 | 2 | | 2 | 1 | <- Since the above already exists, an error will be thrown when inserting --- --- </pre></p>
P粉378264633P粉378264633413 days ago467

reply all(2)I'll reply

  • P粉146080556

    P粉1460805562023-09-04 12:21:14

    You can use triggers to enforce execution. But I can't think of a good way to achieve this using UNIQUE KEY constraints.

    If you change the way you store the values ​​so that they are in a single column, in multiple rows of the attached table, it will be easier to use UNIQUE KEY to enforce uniqueness.


    If you want to indicate related items:

    CREATE TABLE item_group (
      group_id INT AUTO_INCREMENT PRIMARY KEY
    );
    
    CREATE TABLE item_group_members (
      group_id INT NOT NULL,
      member_id INT NOT NULL,
      PRIMARY KEY (group_id, member_id)
    );
    
    INSERT INTO item_group_members VALUES (1, 1), (1, 2);

    If you need each member to appear in only one group:

    ALTER TABLE item_group_members ADD UNIQUE KEY (member_id);

    reply
    0
  • P粉186017651

    P粉1860176512023-09-04 11:25:21

    Define 2 virtual generated columns, respectively the minimum value and the maximum value, and set unique constraints on them:

    CREATE TABLE tablename (
      a INT NOT NULL, 
      b INT NOT NULL,
      x INT GENERATED ALWAYS AS (LEAST(a, b)),
      y INT GENERATED ALWAYS AS (GREATEST(a, b)),
      UNIQUE (x, y)
    );

    ViewDemo.

    Or, for MySql 8.0:

    CREATE TABLE tablename (
      a INT NOT NULL, 
      b INT NOT NULL,
      UNIQUE ((LEAST(a, b)), (GREATEST(a, b))) -- 不要忘记括号 
    );

    ViewDemo.

    reply
    0
  • Cancelreply