简体   繁体   English

创建具有多个可选搜索字段的MYSQL查询

[英]Creating a MYSQL query with multiple optional search fields

I'm create a user search where a user can search for other users based on username, language and/or location. 我正在创建一个用户搜索,其中用户可以根据用户名,语言和/或位置搜索其他用户。 At least one field is required so for example, you can search for just username, or username and location etc. 至少需要一个字段,例如,您可以仅搜索用户名,用户名和位置等。

I'm having difficulty writing a MYSQL query which takes into consideration that some parameters can be blank. 我在编写考虑到某些参数可以为空的MYSQL查询时遇到困难。 I've tried using a maximum of two paramaters at the moment: 我目前尝试使用最多两个参数:

PHP/MYSQL (PDO) PHP / MYSQL(PDO)

$data = json_decode(file_get_contents("php://input"));
$user = $data->user; //'null' if left blank 
$location = $data->location; //'null' if left blank


$sql = "SELECT user, spokenLanguages, profileImage 
        FROM users WHERE user LIKE :user 
        AND (town = LOWER(:location) OR country = LOWER(:location))";

This works perfectly if $user and $location are defined, but I only need the location WHERE clause included if $user is defined and $location isn't equal to null . 如果定义了$ user和$ location,这将非常有效,但是如果定义了$ user且$ location不等于null ,那么我只需要包含location WHERE子句。 Similarly if $location is defined and $user is null , the user clause shouldn't be considered. 同样,如果定义了$ location且$ user为null ,则不应考虑user子句。 Is there any quick method of doing this that I'm unaware of? 有什么我不知道的快速方法吗? Or will it be a case of extending the query with a if/else statements? 还是用if / else语句扩展查询的情况?

Any help will be appreciated. 任何帮助将不胜感激。

You might be better off constructing different queries based on what conditions are defined. 您最好根据定义的条件构造不同的查询。 This makes it easier to optimize them. 这使得优化它们变得更加容易。

If you want to put the logic in a single query, I think you want: 如果您想将逻辑放在单个查询中,我认为您想要:

WHERE (:user IS NULL OR user LIKE :user) AND
      (:location IS NULL OR LOWER(:location) IN (town, country))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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