Help with SQL query

Asked

Viewed 21 times

0

I have 3 tables:

enterprise:

id integer
nome string

category:

id integer
idEmpresa integer
nome string

tag:

id integer
idEmpresa integer
nome string

I am consulting as follows:

SELECT
distinct(e.nome),
e.id,
e.logo
FROM empresas e,
tags t
where (e.nome like '%texto%'
or e.subcategoria like '%texto%'
or t.tag like '%texto%')
and t.idEmpresa = e.id
and e.logo is not null
order by rand()

It queries correctly, but only if there is a registered tag linked to the company, if it does not exist, it ignores the registration.

How to search a company by name, category or tag, regardless of having a registration tag?

  • This form of select 'select from Tabela1, table2 ...' Make an INNER Join, you need a left Join

1 answer

1


Use the clause LEFT JOIN, because it will take all independent tag registrations or not. Also, using JOIN it is no longer necessary to make projection between the tables filtering by WHILE, that is to say, ... and t.idEmpresa = e.id ... it is no longer necessary.

SELECT distinct(e.nome), e.id, e.logo
FROM empresas e
LEFT JOIN tags t ON  e.id = t.idEmpresa
where (e.nome like '%texto%'
or e.subcategoria like '%texto%'
or t.tag like '%texto%')
and e.logo is not null
order by rand()

Following are other types of Union, which can help you solve other problems.

Outros tipos de JOIN

  • opa, continues the same way. I type the name of a company that does not have registered tags and it is not listed

  • Try running without Where and Order by, see if all entries are displayed. If yes the problem is in the WHERE clause

  • 1

    yes, the mistake was in and t.idEmpresa = e.id, because I already had the same one in Join. Valleu

Browser other questions tagged

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