Use INNER JOIN with WHERE clauses

Asked

Viewed 154 times

0

Guys, I am reassembling a system before in ASP now in PHP already with database loaded and mounted, but I need to do some filters where I need to fetch data from at least 3 different tables and maybe more in the future (But I will review this bank because it will probably get too much load for the server).

I set up this structure, but it seems that my WHERE doesn’t work properly, in fact I imagine I’m not applying it properly. What I did:

SELECT * FROM tb_despesas
INNER JOIN tb_contas ON tb_despesas.id_condominio = tb_contas.id_condominio
INNER JOIN tb_contrato_aluguel ON tb_despesas.id_condominio = tb_contrato_aluguel.id_condominio
WHERE (tb_despesas.id_condominio = 17 AND tb_despesas.mes = 11 AND tb_despesas.ano = 2018)
LIMIT 10

I need to get from the table tb_despesas, the entries of accounts relating to mes 11 and ano 2018 for example for condominium with id 17. But I need to take for example the value of a field called aluguel that is inside tb_contrato_aluguel, also need to get the name of the accounts that are in tb_contas.

But this search I do does not use the WHERE clause. And it brings thousands of results kind of repeating the values of tb_despesas in other tables.

A better example. Currently my tb_expenses have only 2 accounts for this month 11. In other words, I should just search the other tables, the account names and the rent for these two accounts and stop here. I applied a limit 10 just to see how many more returned. And it was more or less like this the return (I tried to extract by Navicat)

Content returned by query

What would be the correct logic to follow? Apparently I am using WHERE incorrectly, or INNER JOIN in a way that I cannot apply my conditions.

Thanks a lot, guys.

  • The point is that when you do the Inner Join it brings all the rows from the other table so more lines appear. if you select in tb_contas with id = 17 you will see that there are several Lines for that id

  • That’s true. But I thought it would only bring results from the "parameter" of WHERE. I thought I’d do it by PHP, do a search first on tb_despesas and for each result made a new search in the bank. However at the end of the code so afraid of getting too heavy.

No answers

Browser other questions tagged

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