简体   繁体   中英

multiple search criteria

I'm using the following query, but I currently have to enter a value in every parameter for the query to work. Is there a way of making the parameters optional, so that 1 or more values will return a result?

SELECT * FROM film
WHERE day LIKE '%day%'
AND month LIKE '%month%'
AND year LIKE '%year%'

something like

 function queryData(year,month,day) 

 declare Y

 if year == nothing
     Y = '%'
 else
     Y = '%' + year + '%'

 declare M

 if month == nothing
     M = '%'
 else
     M = '%' + month + '%'

 declare D

 if day == nothing
     D = '%'
 else
     D = '%' + day + '%'

 return result of :

 SELECT * FROM film
 WHERE day LIKE D
 OR month LIKE M
 OR year LIKE Y

Why don't you create your query dynamically? Depending on the parameters you have, append the filters dynamically.

eg:

string query = "SELECT * FROM film";
string paramenters = string.empty;

if(day!= string.empty)
  parameters = " Where day LIKE '%day%'";

if(month != string.empty)
{
  if(parameters != string.empty)
     parameters += "AND month LIKE '%month%'";
  else
     parameters = "WHERE month LIKE '%month%'";
}

and so on....

In this case you won't get extra results that you will get with OR .

SELECT * FROM film
WHERE day LIKE '%day%'
OR month LIKE '%month%'
OR year LIKE '%year%'

You will still be providing all three parameters, but it won't matter if they are blank or NULL, matches will still return from the ones that aren't blank.

Using OR instead of AND changes the logic of the query. It doesn't make the parameters optional. The way to go is not using the parameters you are not using. I don't know any other way.

我会将每个参数的默认值设为%,当有人填写参数时,我会传递%value%

I've not tested, but your query looks like it should work as long as you make sure that the unused parameters are empty strings. eg

day = ""
month = "dec"
year = "2008"

would make your query:

SELECT * FROM film
WHERE day LIKE '%%'
AND month LIKE '%dec%'
AND year LIKE '%2008%'

'%%' should match any string as long as it's not NULL.

thanks for your help folks I ended implementing the following. works a treat

if year == nothing
   Y = ''
else
   Y = '%' + year + '%'

If you wish for a non-dynamic query, something like this will work:

SELECT * FROM film
WHERE (:daysearch is null or day LIKE :daysearch)
AND (:monthsearch is null or month LIKE :monthsearch)
AND (:yearsearch is null or year LIKE :yearsearch)

Although, I do wonder if there is a performance hit on the database.

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