Search in related table

Asked

Viewed 102 times

-1

I have a search script that scans up to three fields of a table called products, now I need to do a search in a table called brand, the product table has the id_brand that relates to the brand table, but I’m not able to implement.

The research is like this:

$pesquisa = $_REQUEST['s'];
$pesquisa = (strtolower($pesquisa));    

// Agrupando campos no concat.
$campo = 'CONCAT(descricao, " ", resumo, " ", detalhes, " ", codigo_msb)';
// dividindo as palavras pelo espaço
$palavras = explode( " ", $pesquisa );  
// eliminando ítens vazios 
$palavras = array_filter($palavras);

// Inicializando a variável
$where = '';
$cola = 'WHERE ';

foreach ($palavras as $palavra) {
  // Removendo espaços em branco
  $palavra = trim($palavra);      
  $palavra = mysql_real_escape_string($palavra, $conexao); 
  $where .= $cola.$campo.' LIKE "%'.$palavra.'%" ';
  $cola = 'AND ';
}

mysql_select_db($database_conexao, $conexao);
$query_rsBusca = "SELECT 
                      produtos.id_marca,                          
                      marca.descricao AS marca  
                    FROM
                      produtos
                      INNER JOIN marca ON (produtos.id_marca = marca.id_marca) ".$where." ";
$rsBusca = mysql_query($query_rsBusca, $conexao) or die(mysql_error());
$row_rsBusca = mysql_fetch_assoc($rsBusca);
$totalRows_rsBusca = mysql_num_rows($rsBusca);

The products table has the id_brand that relates to the brand table and need to do a search by brand name.

The error that is occurring is this:

Column 'descricao' in where clause is ambiguous
  • The question is about some PHP logic or about the SQL command? If it’s about SQL, you can make the question clearer by showing only the SQL code. Also, write down what you have tried so far and the problems encountered.

  • Hello @Caffe, yes, my question is about SQL, I’m doing a Join but the same is failing.

  • Where is JOIN then? It doesn’t appear in the code you posted. And what do you mean by "it’s failing"? There’s an error?

  • I just updated the question with Join, but how do I use the Concat to search the fields in the products table without reference the table marks the error occurs.

2 answers

2


The error is there at the beginning of your code (the explanation is what Fernando said, there is more than one column with the same name involved in the query):

$campo = 'CONCAT(descricao, " ", resumo, " ", detalhes, " ", codigo_msb)';

The solution depends on what description you want to use on WHERE. Assuming it’s the product:

$campo = 'CONCAT(produtos.descricao, " ", resumo, " ", detalhes, " ", codigo_msb)';

About your last comment, this:

WHERE produtos CONCAT(...

should be:

WHERE CONCAT(...
  • Hello @bfavaretto, I can not understand, whenever I change the reference, ie the alias continued with the error, see the message:You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'CONCAT(products.Description, "", summary, "", details, "", code_msb) LIKE "%s' at line 6

  • echo looks like this: SELECT p.id_marca, m.Description AS marca FROM produtos as p INNER JOIN marca as m ON (p.id_marca = m.id_marca) WHERE produtos CONCAT(produtos.Descricao, " ", resumo, " ", detalhes, " ", codigo_msb) LIKE "%sofa%"

  • @adventistapr I edited the answer.

1

The error you posted is already explicitly telling you what the error is. The following is the table produtos should also contain a column called descricao, right? Then how are you not using alias in your query, this error is occurring: Column 'descricao' in where clause is ambiguous, as you posted in the question. Because the database does not know which table you want to use the column descricao, since she’s on both tables.

So what you should do is this:

  • Place alias in the query in your tables;
  • Use the alias to indicate from which table you want the column explicitly;

Follow the modified code:

// modifique seu `where` que é o que está causando o problema
// coloquei como alias "p ou m", pois não sei de qual tabela você quer
$where .= $cola.'p ou m'.$campo.' LIKE "%'.$palavra.'%" ';

// adicione o alias a sua consulta
$query_rsBusca = "SELECT 
                      p.id_marca,                          
                      m.descricao AS marca  
                    FROM
                      produtos as p
                      INNER JOIN marca as m ON (p.id_marca = m.id_marca) ".$where." ";

Or how I realized that instead of alias you were using the table name that works similar to the alias. You just can’t where add the table name to specify which is the column of the where:

// coloquei como alias "produto ou marca", pois não sei de qual tabela você quer
$where .= $cola.'produto ou marca'.$campo.' LIKE "%'.$palavra.'%" ';

Me, to avoid that kind of trouble, I’m used to default to always use alias in my queries for all fields even if they are not ambiguous.

Your second doubt(in the comments), is like @bfavaretto, quoted:

WHERE produtos CONCAT(...

should be:

WHERE CONCAT(...

Code (second doubt) taken from @bfavaretto’s reply

I created an iterative example of the complete solution, here.

  • Hello @Fernando, thank you so much for having responded, I made the changes according to your model, now I’m getting a message, see: You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'CONCAT(description, ", summary, "", details) LIKE "%anc%"' at line 6

  • @adventistapr, now seems to be an SQL error, from an echo in $query_rsBusca before executing the query, and post the full SQL that is running, so you can try to help.

  • echo:SELECT p.id_marca, m.Description AS marca FROM produtos as p INNER JOIN marca as m ON (p.id_marca = m.id_marca) WHERE produtos CONCAT(Description, ", abstract, ", ", details) LIKE "%anc%" You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'CONCAT(Description, "", summary, "", details) LIKE "%anc%"' at line 6

  • Your second question is as @bfavaretto quoted, you should remove "products" before CONCAT. I made a online example of your problem to help you understand your structure, take a look at your corrected SQL.

  • @adventistapr, I edited the reply, complementing with the information relating to this second doubt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.