Is there any way to merge multiple SELECTS into just one query?

Asked

Viewed 814 times

0

I have a page where I will have to make several queries to the bank. At the moment, they are a total of three tables. They are: cadastro, publicacoes and estilo. Currently I do as follows:

SELECT nome, sobrenome, usuario, email FROM cadastro WHERE usuario = "$usuario" LIMIT 1;

SELECT conteudo, data, hora, usuario FROM publicacoes WHERE usuario = "$usuario" ORDER BY id LIMIT 5;

SELECT cor1, cor2, cor3, usuario FROM estilo WHERE usuario = "$usuario" LIMIT 1;

All queries are made and then I manipulate each query through the foreach....

My question is: Is there any way to join all these querys in a single query, thus leaving the code more "clean" and performative?

  • Yes it is possible, in which case you need to do Join, you can start here

  • I had already seen this question yesterday. But the question is: can you use Join even without relating the tables (which is my case)? Or I’m full of shit?

  • If I understand correctly, the information they have in common is the field usuario he will be the joint criterio.

  • 1

    SELECT * FROM (SELECT C.*, P.*, E.* FROM cadastro as C
LEFT JOIN publicacoes AS P ON C.usuario = P.usuario
LEFT JOIN estilo AS E ON C.usuario = E.usuario) RESULTADO WHERE usuario = '".$usuario."'

1 answer

2

I think this query solves your problem, you can join them using Internet as it has the user reference ( Whereas user is unique )

     SELECT cadastro.nome, cadastro.sobrenome, cadastro.usuario, cadastro.email,publicacoes.conteudo, publicacoes.data, publicacoes.hora, estilo.cor1,estilo.cor2, estilo.cor3 
     FROM publicacoes INNER JOIN cadastro ON cadastro.usuario =publicacoes.usuario 
     INNER JOIN estilo ON estilo.usuario = publicacoes.usuario 
     WHERE usuario = "$usuario" limit 5

Browser other questions tagged

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