Conditional clause AND Mysql

1

This query receives two parameters, what I intend is that the second conditional participates in the query only if the value it receives is greater than 0, that is to say that AND fk_id_b = ? is evaluated only if its value is greater than 0. if not that the query ends in WHERE fk_id_a =? Is it possible?

SELECT * FROM tabla 
WHERE fk_id_a = ?
AND fk_id_b = ?

Thank you ...

    
asked by Richard Collao Olivares 22.01.2017 в 22:57
source

3 answers

2

Just to clarify the question a bit, I'm going to assign names to the 2 parameters instead of using the question mark:

SELECT * FROM tabla 
WHERE fk_id_a = :paramA
AND fk_id_b = :paramB

Proposed solution using XOR

The solution proposed by OP is:

SELECT * FROM tabla 
WHERE fk_id_a = :paramA
AND ((fk_id_b = :paramB AND fk_id_b > 0)
XOR (1=1))

This solution is not only difficult to understand, it is not correct either.

Mathematically, a XOR b equals: (a AND (NOT b)) OR ((NOT a) and b) .

So the query equals:

SELECT * FROM tabla 
WHERE fk_id_a = :paramA
AND (((fk_id_b = :paramB AND fk_id_b > 0) AND 1<>1)
OR  ((fk_id_b <> :paramB OR fk_id_b <= 0) AND 1=1))

And because the expressions 1=1 and 1<>1 always evaluate true and false respectively, the query can actually be simplified to:

SELECT * FROM tabla 
WHERE fk_id_a = :paramA
AND (fk_id_b <> :paramB OR fk_id_b <= 0)

To a certain extent, I can see how the query could give the impression of working with negative numbers, but it will definitely give erroneous (even opposite) results for paramB positive values.

Corrected query

If the desire is to ignore the second condition in the query if paramB is zero or less, the usual way to do it is as follows:

SELECT * FROM tabla 
WHERE fk_id_a = :paramA
AND (fk_id_b = :paramB OR :paramB <= 0)

Again, I just used the syntax :paramA and :paramB to clarify a bit the query and be able to differentiate the 2 parameters, but you will have to adjust the syntax in your program to work properly. Additionally, you made no mention of having to manage null values, so I did not worry about this point.

    
answered by 30.01.2017 в 23:07
1

test this, in case the second parameter is less than or equal to 0, the condition fk_id_b=segundo_parametro will not be evaluated:

SELECT * FROM tabla 
WHERE fk_id_a = ? AND IF((? >0), fk_id_b = ?,TRUE)
    
answered by 01.02.2017 в 18:01
0

I found a solution, I do not know if it will be the most appropriate, but at least it complies with the requirements:

SELECT * FROM tabla 
WHERE fk_id_a = ?
AND ((fk_id_b = ? AND fk_id_b > 0)
XOR (1=1))
    
answered by 23.01.2017 в 01:19