I
I
Ivan Filatov2016-03-15 16:53:12
SQL
Ivan Filatov, 2016-03-15 16:53:12

How to implement a SELECT query with multiple WHERE AND combinations?

There is a DB on MSSQL, in it the MyTable table with a heap of columns, "name", "class", "type", for example.
There is a store with many parameters. For example, "name", "class", "type"
can all be NULL.
The task is to implement a SELECT query with an enumeration of all possible WHEREs, depending on which storage parameters are not NULL.
example
if all parameters are NULL if name is specified: if 2 parameters, then more is added , etc. so far I have thought up only to do unloading of ALL records in the tmp-twin table, and then through sequential enumeration of all input parameters to do cleaning of the tmp table. and at the end of the storage to give the result.
SELECT * FROM MyTable
SELECT * FROM MyTable WHERE name like %text%
AND class like %class%

SELECT * FROM MyTable WHERE *тут все собранные условия*

Or do I want too much?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wkololo_4ever, 2016-03-15
@NYMEZIDE

SELECT * FROM MyTable WHERE (@name is NULL OR Name LIKE '%'[email protected]+'%') AND (@class is null OR Class LIKE '%'[email protected]+'%')
etc.
If there are many parameters, then I advise you to addoption(recompile)

A
Anton Shcherbakov, 2016-03-15
@WestTrade

// поступили какие-то данные влияющие на поиск и условия
$a = $_POST['a']; // объявили переменную, допустим забрали данные с POST
$text = "some text";

Just through the condition:
if ($a == 0) {
  $Paste = "MyTable.`id` = 1";
} else if ($a == 1) {
  $Paste = "MyTable.`name` LIKE '%".$text."%'";
}

Or through an array into which we type parameters:
$array = array();

if ($a == 0) {
  // немного рагульно цепляем AND, через проверку длины массива
  if (strlen($array) > 0) {
    $array[] = "AND MyTable.`id` = 1";
  } else {
    $array[] = "MyTable.`id` = 1";
  }
}
if ($text == "some text") {
  if (strlen($array) > 0) {
    $array[] = "AND MyTable.`name` LIKE '%".$text."%'";
  } else {
    $array[] = "MyTable.`name` LIKE '%".$text."%'";
  }
}
$Paste = join(" ", $array); // объединяем через пробел

Forming a future request:
$sql = "
  SELECT * 
  FROM MyTable 
  WHERE ".$Paste."
";

We send $sql to the call, that's it, we are great!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question