doumao1519 2013-11-30 23:25
浏览 81
已采纳

SQL查询。 如果column =特定值,则返回all

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.

  • 写回答

2条回答 默认 最新

  • duanqun9618 2013-11-30 23:31
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?