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.