简体   繁体   中英

how to optimize inner join

I have two tabels. They are in Heidi I need table like: Rezult

I try next SELECT:

    SELECT  accounts.name, accounts.account_id,date,  
  (case  when accounts.account_id = results.account_id then date  end) AS Dat,  
results.account_id 
FROM results 
INNER JOIN accounts 
group by date,dat,name 
order by accounts.account_id ,date

But I have unneeded fields. help get rid of them.

Additionally: I must show table like this:

--------------------01.2010----02.2010-----03.2010---nextDate

Revenues ----------'x'------------'x'---------'null'---------------------

Personal Costs-----'x'------------'x'---------'x'---------------------

Amortisation---------'x'------------'x'---------'null'---------------------

Summa---------------'3x'-----------'3x'---------'1x'---------------------

I use next select:

SELECT 
GROUP_CONCAT(revenues SEPARATOR ';')as Renenues, 
GROUP_CONCAT(personal  SEPARATOR ';')as Personal, 
GROUP_CONCAT(amortisation  SEPARATOR ';')as Amortisation
from (SELECT  date, 
sum(case  when accounts.account_id = 1 then 1 else 0 end) as revenues,
sum(case  when accounts.account_id = 2 then 1 else 0 end) as personal ,
sum(case  when  accounts.account_id = 3 then 1 else 0  end) as amortisation
from accounts
left JOIN results on accounts.account_id = results.account_id
group by date
) t
UNION ALL
SELECT
sum(case  when results.account_id = 1 then 1 ELSE 0  end) ,
sum(case  when results.account_id = 2 then 1 else 0 end) ,
sum(case  when  results.account_id = 3 then 1 else 0  end) 
 from results

Then I will show table row from my string: 'GROUP_CONCAT'. Possible to make such that SELECT without knowing the number of 'accounts.account_id' or optimize this SELECT? I tried the first SELECT but get a lot of unnecessary information.

You should modify your query to be like

SELECT  accounts.name, 
accounts.account_id as accounts_account_id,
accounts.date,  
results.account_id  as results_account_id
FROM results 
LEFT JOIN accounts ON accounts.account_id = results.account_id
group by accounts.date,accounts.name 
order by accounts.account_id ,accounts.date;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM