do an if in the where of a select

0

How can I do an if in the where in mysql

I want to validate this

$parametro= mujer
$parametro= Hombre
$parametro= Indistinto

select * from tabla s

if field s.sexo = $parametro OR if the parameter is called No matter what the whole table brings me

    
asked by Carlos Enrique Gil Gil 11.06.2018 в 18:17
source

2 answers

3

You must create a stored procedure to which you pass as a parameter the sex and filter the data according to that:

DROP PROCEDURE IF EXISTS obtenerData //

CREATE PROCEDURE 
  obtenerData( parametro VARCHAR(20) )
BEGIN
   IF(parametro = 'Indistinto') THEN
      -- Devuelves toda la tabla si es 'Indistinto'
      SELECT * FROM tabla 
   ELSE
      -- Sino devuelves data de acuerdo al parámetro
      SELECT * FROM tabla WHERE tabla.sexo = parametro
   ENDIF
   ;  
END 
//

DELIMITER ;

Then you call that stored procedure according to your parameter

call obtenerData('Hombre');
call obtenerData('Mujer');
call obtenerData('Indistinto');
    
answered by 11.06.2018 / 18:40
source
4

It would be like this:

select * from tabla s Where (s.sexo = $parametro) Or ($parametro = 'Indistinto')
    
answered by 11.06.2018 в 18:45