Select Union same table

Asked

Viewed 440 times

0

Could anyone help me with this problem? The query below throws the following error:

#1054 - Unknown column 'u.idocorrencia' in 'Where clause'

SELECT DISTINCT * FROM(
        (SELECT  o.*, u.nome AS requerente FROM ocorrencia o, utilizador u WHERE u.idutilizador = 2 AND perfil = 2)
        UNION ALL
    (SELECT  o1.*, u1.nome AS tecnico FROM utilizador u1, ocorrencia o1 WHERE u1.idutilizador != 2 AND u1.perfil = 1) 
    ) AS t WHERE u.idocorrencia = u1.idocorrencia and u.requerente <> u1.tecnico

The tables involved in the query are:

tabela utilizador (idutilizador, nome, perfil);

tabela ocorrencia (idocorrencia, ocorrencia, descricao);

tabela utilizador_ocorrencia (ocorrencia_id, utilizador_id);
  • What error? What do you expect to return with this query? Click [Edit] and add these details to the question.

  • #1054 - Unknown column 'u.idocorrencia' in 'Where clause'

  • I hope to resume the reputation | Subject | Description | Applicant | Technical

  • Note: applicant and technician are part of the user table

1 answer

1

You’re using a sub-query. From "as t", you can no longer refer to the alias "u" and "U1" of the sub-query, that is, of the internal tables. Maybe it would be better if you put the structure of the tables. But see if the query below can help you:

  SELECT distinct o.*, u.nome as requerente, u1.nome as tecnico 
  FROM ocorrencia o
  left join utilizador u  on (o.idocorrencia = u.idocorrencia)
  left join utilizador u1 on (o.idocorrencia = u1.idocorrencia)
  where ((u.idutilizador = 2 AND perfil = 2)
    or (u.idutilizador != 2 AND perfil = 1))
    AND u.nome <> u1.nome

or this :

select o.*, u.nome as requerente, u1.nome as tecnico
from ocorrencia o 
  inner join utilizador_ocorrencia uo on (o.idocorrencia = ocorrencia_id)
  left join utilizar u on (u.idutilizador = uo.utilizador_id and u.perfil = 2)
  left join utilizar u1 on (u1.idutilizador = uo.utilizador_id and u1.perfil = 1)
where u.idutilizador <> u1.idutilizador    
  • Good Eduardo, it didn’t work

  • Send the table structure.

  • I made a change in the query of the answer. Do another test there. If it does not work, send the structure of the tables so that we can help you.

  • Eduardo, you have posted two apparently identical answers. I suggest that you join them only in this and delete the other.

  • 1

    Done @Diegof. The answers had some differences, but you’re right to put it all together. Thanks!

Browser other questions tagged

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