How to Sub Select in SQL

Asked

Viewed 1,938 times

1

I wonder if anyone can help me because I could not do the command sub select between two tables, someone could help me?

I need to pull the name of the book that’s on the table book along with the sales chart data.

Table vendas:

inserir a descrição da imagem aqui

Table livros:

inserir a descrição da imagem aqui

  • would not be a Join and not a subselect?

  • If I’m not mistaken the command to do this is the INNER JOIN.

2 answers

4


Answering your question:

What do you want is not subselect and yes JOIN.

Example of JOIN whereas your sale table will always have 1 book for sale:

SELECT * 
FROM VENDAS VD
INNER JOIN LIVROS LV ON LV.IDLIVRO = VD.IDLIVRO

Filtering some fields:

SELECT VD.IDVENDA, LV.TITULO, LV.PRECO
FROM VENDAS VD
JOIN LIVROS LV ON LV.IDLIVRO = VD.IDLIVRO

(In the examples see that I used INNER JOIN and JOIN. In this case it works the same way, because using only JOIN he assumes as if he were INNER.)


Extra examples:

To bring ALL values of table VENDAS even though nay completed the field IDLIVRO on the table VENDAS, use the LEFT JOIN:

SELECT * 
FROM VENDAS VD
LEFT JOIN LIVROS LV ON LV.IDLIVRO = VD.IDLIVRO

To bring ALL values of table LIVROS even though nay completed the field IDLIVRO on the table VENDAS, use the RIGHT JOIN:

SELECT * 
FROM VENDAS VD
RIGHT JOIN LIVROS LV ON LV.IDLIVRO = VD.IDLIVRO

Reference on JOINS it would be nice to see as an example:

Select only tuples from a table with JOIN

  • Thanks guy :D, I said select because that’s what the teacher taught, but I saw that by its way is much easier :D.

  • @leandror what I did was a select (query). What’s wrong is saying "subquery". That’s something else for another purpose.

  • @leandror got any questions? If not, choose an answer and mark it: HOW TO SCORE

-1

The Join would be a solution as mentioned above, you can also do the following:

select * from Vendas
where idlivro in (
  select idlivro from livros where idgenero = 1
);
  • 2

    diego, is totally incorrect your answer. Mainly this: in ( select idlivro where idgenero = 1 ); that does not even have the table. Always try to publish a reply, put in detail, as this helps avoid erring them.

  • @Rbz guy did not understand why to say it is wrong, this is a subselect, is not the ideal to make understand that it is more time consuming for the bank, but it is a way to do without using Join.

  • diego, your select is not what was asked in the question, and at least it works, as I showed the excerpt in the comment above.

  • @diego your subselect doesn’t work basically because it doesn’t have from; if you add and fix, you may become a valid alternative.

  • @rLinhares worth, I had not realized that I had forgotten the from

Browser other questions tagged

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