Validation of 2 fields in a table

0

I have a table in Mysql, with a DESCRIPTION field and another Grade, how do I make the set of the two fields can not be repeated?

EXAMPLE

If it is:

DESCRIPTION: abcde GRAU: 12345 OK

And if it is:

DESCRIPTION: abcde GRAU: 67891 OK

But if it is:

DESCRIPTION: abcde GRAU: 12345 NO

Understand? type, two fields can not be replayed together, but one can.

    
asked by anonymous 17.06.2018 / 03:51

2 answers

0

You can define multiple columns as your primary key, for example:

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

So ID and LastaName can repeat but can not repeat together

    
17.06.2018 / 04:22
1

I recommend using a select to check if there are such parameters previously registered, being as follows:

SELECT count(desc) as 'qtdDesc' FROM table WHERE desc = 'descAserInserida' AND grau = 'grauAserInserido';

Then just check if 'qtdDesc' > 0, so do not register, otherwise you will register.

  

How do I use this when entering data into the table?

     

Use as follows, example with mysqli

$conn = new mysqli ("localhost", "USUARIO", "SENHA", "nome_DB");

$result = $conn->query("SELECT count(descricao) as 'qtdDesc' FROM table WHERE descricao = '$descAserInserida' AND grau = '$grauAserInserido'");

$row = $result->fetch_row();
if ($row[0] > 0) {
    //existe, não insere
    echo "existe";
} else {
    echo "não existe";
    $sql = "INSERT INTO table (descricao,grau) VALUES('$descAserInserida','$grauAserInserido')";
    $result = mysqli_query($conn,$sql);

}
$conn->close();
    
17.06.2018 / 04:14