Validation of 2 fields in a table

Asked

Viewed 84 times

0

I have a table in Mysql, with a DESCRIPTION field and another Degree, as I do so that the set of the two fields cannot 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

Got it? Like, two fields can’t be rethought together, but one can.

  • No, I don’t understand. The third example is : adcde which is different from the first two

  • Know what a primary key originated from two or more columns?

  • @Leocaracciolo kk vc ta right, I wrote wrong corrected ja

  • @Guilhermecostamilam I don’t know, how it works?

  • But do you want to check if there is already a record in the table according to your examples? Easier than taking candy from the hand of a child in the bakery!

2 answers

0

I recommend using a select to find out 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, then do not register, otherwise you 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();
  • how do I use this when entering data into the table?

  • The idea is not to group the results, but not to allow duplicate lines, I believe you misunderstood the question, or so I understood very badly

  • 1

    Ah, GROUP BY only groups the results, in the case of data insertion you can perform a select like: SELECT Count(desc) as 'qtdDesc' FROM table WHERE desc = 'descAserInserida' AND grau = 'grauAserInserido'; and check if qtdDesc > 0, if it is you do not register, and if you’re not registered..

0


You can set 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 the ID and the LastaName can repeat but cannot repeat together

  • Vlw man! of vdd was very afraid looking for that

  • The question is descricao and grau which cannot be repeated. In the case of id have to be AUTO_INCREMENT and Description and grade can not repeat, will not roll. Since you did not adapt the script to match the question, I think it is pertinent to post the source of this script

Browser other questions tagged

You are not signed in. Login or sign up in order to post.