简体   繁体   中英

Sql query. Return all if column = a particular value

I have a small question concerning an SQL query I am using in a PHP project, more precisely my Where Statement.

So let's say I have a table named tab. This table has 3 columns: id, name and position. name is a varchar and position is an int.

What I am trying to do is to find all rows of the table where the values of the colums are equal to the value of variables (Lets call them $name and $pos). So normaly I would simply do something like this:

private function getSqlQuery($name, $pos){
    return "SELECT *
            FROM tab
            WHERE name LIKE '%" . $name . "%' 
            AND position = " . $pos;
}

To clarify, the variable $pos is not strictly integer and could be a char or string and I have control over what value to send in parameter.

Now here is the catch with what I need to do: this query must be able to also return every row that respect the first condition (name = $name) must be returned, regardless of the value of position.

I also cannot use multiple SQL query, I won't go into detail as to why as it would take too long, but I cannot call 2 different query. I can only modify the values of the parameters ($name and $pos).

I need to find some sort of Wildcard, a value to send to $pos so it would return anything. Using LIKE '%%' for name worked, but I have yet to find one for an int value.

I apologize for my poor english.

I never used something like this, but in theory i think it could work:

You could use pass a specific string in $var and check for it with a CASE in WHERE clause. If it is that string you compare position with position, which gives you the results from the first validation:

 SELECT *
 FROM tab
 WHERE name LIKE '%" . $name . "%' 
 AND position = CASE WHEN " .$var. " = 'IGNORE' THEN position ELSE " .$var. "END;

First, I think $var should be $pos :

        SELECT *
        FROM tab
        WHERE name LIKE '%" . $name . "%' AND
              position = " . $pos;

A typical condition would be if you passed in a special value for pos, then you would return all rows that match name. Say that pos must always be non-negative, then you could use -1:

        SELECT *
        FROM tab
        WHERE name LIKE '%" . $name . "%' AND
              (position = " . $pos . " or " . $pos . " = -1)";

The only question is what out-of-range value you can use for the comparison. If there are none, you could change $pos to a string and then use the empty string for this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM