Answer the question
In order to leave comments, you need to log in
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
Projects
Sources
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:
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
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 questionAsk a Question
731 491 924 answers to any question