Answer the question
In order to leave comments, you need to log in
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 *тут все собранные условия*
Answer the question
In order to leave comments, you need to log in
SELECT * FROM MyTable WHERE (@name is NULL OR Name LIKE '%'[email protected]+'%') AND (@class is null OR Class LIKE '%'[email protected]+'%')
etc. option(recompile)
// поступили какие-то данные влияющие на поиск и условия
$a = $_POST['a']; // объявили переменную, допустим забрали данные с POST
$text = "some text";
if ($a == 0) {
$Paste = "MyTable.`id` = 1";
} else if ($a == 1) {
$Paste = "MyTable.`name` LIKE '%".$text."%'";
}
$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); // объединяем через пробел
$sql = "
SELECT *
FROM MyTable
WHERE ".$Paste."
";
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question