M
M
maxxieblh2020-04-24 09:38:17
MySQL
maxxieblh, 2020-04-24 09:38:17

How to form a correct SQL query?

Good day! Difficulties arose with the formation of an SQl query. Let's admit there are following tables in a DB:
Profits
5ea282586b883697564490.png
Projects
5ea281b281474452872911.png
Sources
5ea281bec5e3a111459001.png

In the table Profits incomes are entered. In turn, there is a source of income, there is a category of sources and there are projects.
You need to get the data in the following form:
5ea284c34a27c406180336.png
I made the following query:
SELECT
T2.name as name_proj,
SUM(T1.money) as sum_money,
DATE_FORMAT(date_trans, '%Y-%m-%d') as date

FROM `Profits` as T1

INNER JOIN `Projects` as T2
ON T2.id = T1.project_id

WHERE
T1.project_id IN (1, 2)
AND T1.source_id IN (1, 2)

GROUP BY project, date;

In the form on the site, you can select projects and sources for them and get data grouped by projects and the date of the transaction. But it became necessary to choose, in addition to the sources themselves, their categories. Those. in the request, it turns out that there can be id sources and id categories of sources, but how can I correctly compose it so that the request is optimal?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Pankov, 2020-04-24
@maxxieblh

I don't understand what your problem is. do an additional join of sources, add all the necessary fields to the grouping and select, and nothing else will change.
In the presence of indexes, joins on the primary key are effective.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question