Ir para conteúdo
Fórum Script Brasil
  • 0

Problema com Seleção


Rafael Castelhano

Pergunta

Meu problema é o Seguinte:

Num sistema de RH, é inserido os dados de candidatos as vagas da organização, e tenho que montar um script para retornar a relação de candidatos que atende a uma serie de requisitos que seram passados no momento da consulta.

A estrutura da tabela é a seguinte:

+----------------------------+

| intCandidatoId (chave) |

| intCargoPretendido |

| blnSexo |

| strEstadoCivil |

| intFilhos |

+----------------------------+

A consulta deve retornar os canditados que atendem a um ou mais dos criterios passados (até ai é tranquilo) e exibir eles na ordem dos que melhor atendem (ai ta o problema).

Ou seja, os candidatos deveram estar classificados de acordo com a "melhor pontuação", ou seja os que atendem mais requisitos.

Minha duvida é se só com SQL consigo resolver este problema, ou vou presisar usar algumas funções em PHP, e como fazer isto......

Link para o comentário
Compartilhar em outros sites

4 respostass a esta questão

Posts Recomendados

  • 0

Boa noite ESerra,

na verdade este campo não existe na tabela.... seria no meu exemplo o campo que armazenaria a contagem de quantos criterios foram atendidos por cada candidato.

Eu estava pensando em um código assim:

SELECT intCandidatoId, strNome, Count( strNome =2
OR blnSexo =1
OR intFilhos >0 ) AS Avaliacao
FROM rh_candidatos
ORDER BY Avaliacao

Não sei usar muito bem o Count, nem sei se pode fazer isto, a sintaxe não esta dando erro, porem não esta retornando um resultado certo....... (esta trasendo apenas o primeiro registro da tabela com o Avaliacao valendo 4) ??

Link para o comentário
Compartilhar em outros sites

  • 0

Uma das possibilidades é usando pesquisa por full text a outra é usando uma condição lógica do seu comando SQL, veja o exemplo de uma pesquisa por relevancia open source:

<?php
/*
 *      search.php
 *
 *      Copyright 2007 - 2008 | JAGS-CMS.com
 *      
 *      Author: Barry Munro <sitemaster16<at>gmail<dot>com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 *      
 */

if (!defined('WEB_ROOT')) {
    exit;
}

require_once 'config.php';


if (isset($_GET['search'])) {
    $search = $_GET['search'];
    $queryString = "search=$search";
} else {
    $queryString = '';
}

if (isset($_GET['search']) && $_GET['search'] == '') {
    $errorMessage = '<div class="error">No Search Term Provided</div>';
}


if (isset($_GET['page']) && (int)$_GET['page'] >= 0) {
    $page = (int)$_GET['page'];
} else {
    $page = 0;
}


if (isset($search) && $search !== '') {


//get the mysql and store them in $result
//change whatevertable to the mysql table you're using
//change whatevercolumn to the column in the table you want to search

// for paging
// how many rows to show per page
if (isset($_GET['resultsperpage'])) {
    $rowsPerPage = $_GET['resultsperpage'];
} else {
    $rowsPerPage = 10;
}

if (isset($_GET['searchInDb'])) {
    $searchDatabase    = $_GET['searchInDb'];
} else {
    $searchDatabase    = dbPrefix.'countrys';
}

if (isset($_GET['searchInDbT'])) {
    $searchTables    = $_GET['searchInDbT'];
} else {
    $searchTables    = 'cntry_name';
}


// get microtime
function getmicrotime()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

// seperate all keywords in the search phrases
$searchChunks = explode(' ', $search);

// make cases for sql query
function getCases($searchTables, $searchChunks)
{

    $cases = '';
    $chunkCount = count($searchChunks) - 1;

    for($i = 0; $i < count($searchChunks); $i++){

        if ($i == $chunkCount) {
            $cases .= "(CASE WHEN $searchTables LIKE '%$searchChunks[$i]%' THEN 1 ELSE 0 END)";
        } else {
            $cases .= "(CASE WHEN $searchTables LIKE '%$searchChunks[$i]%' THEN 1 ELSE 0 END)+";
        }
    }
    return $cases;
}


// make LIKES for sql query
function getLikes($searchTables, $searchChunks)
{

    $likes = '';
    $chunkCount = count($searchChunks) - 1;

    for($i = 0; $i < count($searchChunks); $i++){

        if ($i == 0) {
            $likes .= "$searchTables LIKE '%$searchChunks[$i]%'";
        } else {
            $likes .= " OR $searchTables LIKE '%$searchChunks[$i]%'";
        }
    }
    return $likes;
}


// assign $cases to get the multiple case function
$cases = getCases($searchTables, $searchChunks);
$likes = getlikes($searchTables, $searchChunks);


// start timer
$start_search = getmicrotime();

// get all the data in the db
$sqlT = "SELECT *
        FROM $searchDatabase
        WHERE MATCH($searchTables) AGAINST('$search')";

// if result is none try other search
if (dbNumRows(dbQuery($sqlT)) !== 0) {
$sql = $sqlT;
} else {
$sql = "SELECT *, ($cases) AS relevance
        FROM $searchDatabase
        WHERE $likes
        ORDER BY relevance DESC";
}


// get total results man
$totalResults = dbNumRows(dbQuery($sql));

// get the result number-number of totalresult line
if ($page == 0) {
    $startOS = ($page * $rowsPerPage + 1);
} else {
    $startOS = (($page - 1) * $rowsPerPage + 1);
}

    $stopOS = ($startOS + 9);


$result = dbQuery(getPagingQuery($sql, $rowsPerPage));

// stop timer
$stop_search = getmicrotime();

//calculating the search time
$time_search = ($stop_search - $start_search);


$pagingLink = getPagingLink($sql, $rowsPerPage, $queryString);

echo $errorMessage.'<form method="get" action="search.php">
<p>Search for Something</p><input type="text" value="'.$search.'" name="search" size="25" />
<input type="Submit" value="Search Now">
</form>
';

if (dbNumRows(dbQuery($sql)) == '0') {
echo "<div>No Results for <b>$search</b></div>";
} else {
echo "<div><b>$startOS &ndash; $stopOS</b> of <b>$totalResults</b> Results for <b>$search</b> in ".sprintf("%01.2f", $time_search)." Seconds</div><br /><br />";
}

//grab all the content
while($row = dbFetchAssoc($result)) {
   //the format is $variable = $r["nameofmysqlcolumn"];
   //modify these to match your mysql table columns

   $title=$row["cntry_name"];
   /*
   $message=$r["message"];
   $who=$r["who"];
   $date=$r["date"];
   $time=$r["time"];
   $id=$r["id"];
   */


   //display the row <br> $message <br> $who <br> $date | $time <br>
   echo "$title<br />";
}
echo '<br /><br /><br /><div class="center">'.$pagingLink.'</div>';


} else {
echo $errorMessage.'<form method="get" action="search.php">
<p>Search for Something</p><input type="text" name="search" size="25" />
<input type="Submit" value="Search Now">
</form>
';
}

?>

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...