简体   繁体   中英

SQL search to return if several user inputs are empty

Here is my dillemma, I am trying to implement search for my website, and what I have is multiple comboboxes, and the user can select an option and press search, I do however want to at least return what exists based on their selection, ie if they leave section blank, and only select semester, then I should have something in my result set, or if they select semester, and instructor, and leave the others blank, then I should have something in my result set, unfortunately its not working. Here is my Query.

SELECT * 
  FROM CoursesTaught c 
 WHERE c.Section = :section 
       AND c.CourseName=:courseName 
       AND c.Semester=:semeste 
       AND c.programName=:ProgramName 
       AND c.CoordinatorName=:coordinatorname

Essentially what I want to do is do a check that if empty, or "n/a" then rather than 'AND' do an 'OR' but I can't figure it out.

Build your query dynamically depending on user selection. Similar question with answer how to do this in Java: How to dynamically generate SQL query based on user's selections?

除非您要使用非常丑陋的SQL查询,否则需要使用服务器端语言来评估用户选择,并根据用户选择将其作为查询字符串动态构建查询。

Probably easiest to use the union operator:

http://www.w3schools.com/sql/sql_union.asp

SELECT * FROM CoursesTaught c
WHERE c.Section = :section
union
SELECT * FROM CoursesTaught c
WHERE c.Semester=:semeste

You can create query string manually ie

String query = "SELECT * FROM CoursesTaught c ";
String whereCondition = "";

if(!section.isEmpty)
  if(whereCondition.isEmpty)
     whereCondition = whereCondition + " AND c.Section = '" + section + "'";
  else
     whereCondition = "c.Section = '" + section + "'";

if(!courseName .isEmpty)
  if(whereCondition.isEmpty)
     whereCondition = whereCondition + " AND c.CourseName  = '" + courseName  + "'";
  else
     whereCondition = "c.CourseName  = '" + courseName  + "'";
.
.
.

if(!whereCondition.isEmpty)
   query = query + whereCondition;

And you can pass query string to your executeQuery() method.

You'll probably see the best performance using the method suggested by Jared_S but you can do it with regular sql:

SELECT * 
  FROM CoursesTaught c 
 WHERE (c.Section = :section or :section is null)
       AND (c.CourseName=:courseName or :courseName is null)
       AND (c.Semester=:semester  or :semester is null)
       AND (c.programName=:ProgramName or :programName is null)
       AND (c.CoordinatorName=:coordinatorname or :coordinatorName is null)

This assumes that the missing parameters are null, if not simply change the test to look for an empty string, assuming that's the parameter type.

One drawback to this approach is that you'll end up returning the entire table if all the parameters are null.

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