I Have a view that return to me the customers and sum
of their payment and its work but it take 8 second and when i remove the computed column part from the query it didn't take any time, and i tried to solve this by creating a non-clustered index on tables but its also 8 second, so I'm asking about if there is any method to improve the performance, although i have to use this technique.
my code is
SELECT ID
,NAME
,Total = (
SELECT Sum(Value)
FROM TRANSACTION
WHERE Employee.ID = employee_ID
)
FROM Employee;
Thanks in advance
You can try to use a join with group and see if that is faster:
select employee.id, employee.name, sum(value)
from employee
join transaction where transaction.employee_ID = employee.id
group by employee.id, employee.name
Also - try to avoid to give names that correspond to reserved words - like TRANSACTION
- see https://dev.mysql.com/doc/refman/5.5/en/keywords.html
To hasten up you might want to consider a combined index on Emlpoyee(id,name)
AND an index on Transaction.Employee_ID
- both are neede to make the joins and grouping for this query fast. Check if transaction.employee_ID
has a FK_Constraint
to Employee.ID
- that might help as well.
You could use a join in the subselect with the sum
select e.id, e.name, t.total
from employee e
join (
select employee_ID, sum(value) as total
from TRANSACTION
group by employee_ID
) t on t.employee_ID = e.id
For this query:
SELECT ID, NAME,
(SELECT Sum(t.Value)
FROM TRANSACTION t
WHERE e.Employee.ID = t.employee_ID
) as Total
FROM Employee e;
You want an index on TRANSACTION(employee_ID, Value)
. That should actually give you optimal performance.
You can write this as a join
-- but a left join
:
SELECT e.ID, e.NAME, SUM(t.Value) as Total
FROM Employee e JOIN
TRANSACTION t
ON e.Employee.ID = t.employee_ID
GROUP BY e.ID, e.NAME;
However, the overall GROUP BY
is usually less efficient than the "sub group by" in MySQL (and often in other databases as well).
Try an indexed view on the total
CREATE VIEW totalView
WITH SCHEMABINDING
AS
select employee_ID, sum(value) as total
from TRANSACTION
group by employee_ID
CREATE UNIQUE CLUSTERED INDEX PK_totalView ON totalView
(
employee_id,total
);
Then join to that
select employee.id, employee.name, coalesce(t.total,0)
from employee
left outer join totalView t where t.employee_ID = employee.id
Adjust the join type according to your need.
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.