我在Sql服务器上有一个问题,我要优化。
SELECT user_type_name = CASE user_type_id
WHEN 1 THEN Admin
WHEN 5 THEN Super Admin
WHEN 3 THEN Writer
WHEN 4 THEN Reader
END,
user_can_log = CASE user_inactive
WHEN 1 THEN No
ELSE Yes
END,
(SELECT COUNT(*)
FROM t_fthread
WHERE fthread_creator_userid = user_id) AS number_tickets,
(SELECT COUNT(*)
FROM t_email
WHERE email_to LIKE % + user_email + %
OR email_cc LIKE % + user_email + % ) AS number_emails,
*
FROM t_user
LEFT JOIN t_organisation
ON user_org_id = organisation_id
WHERE user_org_id = 42
ORDER BY user_last_name,
user_first_name
The query takes too much time to run. thanks to query analyzer, I ve identified the part in the query that takes too much time, It s this section:
(select count(*) from t_email where email_to like % +user_email+ % or email_cc like % +user_email+ % ) as number_emails.
I m trying to rewrite the query to still get the number_emails but in every case, it s still very slow.
I ve tried to create the indexes, but it s impossible to create index on user_email and user_cc. Both columns are ntext types and on sql server 2000, it s not possible to create index on theses columns. I ve run analyze the query with Database Engine Tune Advisor and I ve run the recommendations provided by the tools.
CREATE NONCLUSTERED INDEX [_dta_index_t_fthread_15_2073058421__K5] ON [dbo].[t_fthread]
(
[fthread_creator_userid] ASC
)
CREATE STATISTICS [_dta_stat_1365579903_4_3] ON [dbo].[t_user]([user_last_name], [user_first_name])
CREATE STATISTICS [_dta_stat_1365579903_1_5] ON [dbo].[t_user]([user_id], [user_org_id])
CREATE NONCLUSTERED INDEX [_dta_index_t_user_15_1365579903__K5_K1] ON [dbo].[t_user]
(
[user_org_id] ASC,
[user_id] ASC
)
但是,要完成执行还有很多时间。