Home > Software engineering >  Skip rows based on booleans
Skip rows based on booleans

Time:11-29

I am looking for an SQL solution, but have an array in PHP like so:

$booleans = array(true, false, true, false, false);

I know that my SQL query will return exactly the number of booleans in the array.

$query = mysqli_query($db, 'SELECT name FROM fruits');

// Result after some processing

$result = array('apple', 'banana', 'pineapple', 'orange', 'mango');

How can I apply the booleans to my SQL selection to return only the values which indexes in the array are true. Desired outcome:

array('apple', 'pineapple');

For optimization I am not looking for a PHP solution. I want to implement this in SQL during the selection process.

Is this possible in SQL?

CodePudding user response:

This can be made efficient by changing the input. Instead of returning (T, F, T, F, F), replace the T's with the ID of the corresponding row and the F's with a number that doesn't appear in the ID table (such as -1).

So assuming the IDs of the fruits are just the counting numbers (1, 2 etc), the returned array from the example would be (1, -1, 3, -1, -1). Following this change in input, the desired result can be obtained with the query SELECT * FROM fruits WHERE id IN (input array).

  • Related