AND operator doubt in Mysql

Asked

Viewed 38 times

-2

I am making a consultation and I need to show three genres of a Book, as I do to show the 3?

select Livro, Autor from Biblioteca where Genero = 'Romance';

I can get you to show the romance novels, but when I add AND, it doesn’t work.

select Livro, Autor from Biblioteca where Genero = 'Romance' and 'Terror';

  • 1

    Use the "OR" instead of AND

  • but I need you to show the 3, not just one of the 3

1 answer

4

You can use the "IN" to return the options you need.

Would look like this:

SELECT Livro, Autor FROM Biblioteca WHERE Genero IN('Romance','Terror');

Above, records will be returned where "Genero" equals "Romance" or "Terror". If you want to bring from other genres, just add more options in IN.

You can also use the "OR". Behold:

SELECT Livro, Autor FROM Biblioteca WHERE Genero = "Romance" OR Genero = "Terror";

Above, if you want to search for more genres, just add one more "OR" clause and add a new genre "... OR Gender = 'Action'", for example.

The way you were doing, using the "AND", you were trying to bring records that were of the Genero "Romance" and the Genero "Terror", that is, the records would have to be of the two genres at the same time.

OBS: And still has the addendum of its syntax, exemplified in the second question code, also not correct.

You did:

WHERE campo = valor AND valor

And the right one, when using the operator AND, would be:

WHERE campo = valor AND campo = valor

Tip: Try putting the names of the columns and tables of the Mysql database in lower case (mainly the first letter of the word). Use "genero" instead of "genero" and "library" instead of "library".

Good link for you to take a look at operators in Mysql: Devmedia - Operators

  • It worked out! Thank you very much :)

  • @paulconiel, it was nothing. I’m glad it worked. Used the "IN" or the "OR" ?

  • If the answer served you, click on that "V", which is there in the side column of the answer, to accept it and mark the topic as solved.

  • 3

    The way you were doing, using "AND", you were trying to bring in records that were from Genero "Romance" and Genero "Terror" - no, the way he was doing he was inventing syntax, because he used and 'terror' instead of and Genero = 'terror', which would clearly not solve either, but it is advisable, if you edit the answer, to point out this problem as well.

  • Right! I’ll add.

Browser other questions tagged

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