powered by simpleCommunicator - 2.0.50     © 2025 Programmizd 02
Форумы / Caché, Ensemble, DeepSee, MiniM, IRIS, GT.M [игнор отключен] [закрыт для гостей] / Помогите оптимизировать SQL запрос
25 сообщений из 62, страница 2 из 3
Помогите оптимизировать SQL запрос
    #38288923
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
krvsaРанее как-то писалось, что такое

оптимальнее написать так
Код: sql
1.
2.
        WHERE ResponseDate >= '2013-03-01'
        AND DateArchived BETWEEN '2013-03-01' AND '2013-03-31'      


Причем даже местами поменять
Код: sql
1.
2.
3.
4.
        WHERE 
        DateArchived BETWEEN '2013-03-01' AND '2013-03-31'      
        AND 
        ResponseDate >= '2013-03-01'




Дату меняла разным способом- не помогло. Остался изначальный вариант с >= и <=
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38288942
servit
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichkaДату меняла разным способом- не помоглоЕсли запрос работает правильно с between, лучше оставить его, чем с >=, <=vichkaКак мне показать вам планы запросов? Скопировать и вставить здесь как текст или как?Да, давайте сюда как текст.

Но хотелось бы сперва узнать: Вы мои и других участников варианты пробовали? Потому что я до сих пор вижу у Вас like '%'.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38288959
Фотография DAiMor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichkaИзвините за поздний ответ.
Как мне показать вам планы запросов? Скопировать и вставить здесь как текст или как?
Я прицепила ранее файл, кто-то сказал, что не все видно- это все что было, за исключением самих записей.
Как мне тогда вам их предоставить?это я просто, слишком быстро просмотрел не заметил что там все верно.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38288970
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
АленочкаВопросы к автору :
ResponseText берется из таблицы ResponseArchive? или MessageArchive?


ResponseText берется из таблицы ResponseArchive.
Ниже привела пример с полным названием полей.


Аленочкапосмотрите раздел Query Optimization Options , в частности %NOFLATTEN и использование этой опции в подзапросах
http://docs.intersystems.com/cache20081/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_from#RSQL_C22222

Пробовала с %NOFLATTEN - не лучше.

Аленочкатак же думаю что вам могут помочь в форуме по MS SQL Server

Про это тоже думала. Но не уверена- нюансы ли это Cache или SQL?
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38288974
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
servit vichka ,

Статистику по таблицам собирали?

Да, TUNE TABLE все время делаю. Это называется СТАТИСТИКА по-русски? Я даже не знала.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38288991
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Блок А.Н.У вас проблема, что включается использование индекса по MobileNumber, каше считает его оптимальным, но ошибается.
Да, я это тоже поняла. Причем видно как выдаются записи по очереди группами сначала все номера 35383, потом 35385, потом 35386, потом 35387, потом 35389 (когда медленно).
А в быстром варианте они посортированы другим образом (не знаю как), и все записи сразу высвечиваются, без группировок.
Это когда запрс запускается из Management Portal.

Блок А.Н.1. использовать подсказку %Ignoreindices. Не факт, что получится, так как это часть первичного ключа.

Да, не факт. Пробовала отключить индекс, все равно делает то же самое, из-за первичного ключа, как я поняла

Блок А.Н.2. использовать конструкцию
select from
( select ...
)
where MobileNumber ...
Тогда основной запрос не будет использовать индекс, а фильтрация будет уже в промежуточных результатах

Пробовала. Не помогло. Выполняется быстрее может на пару секунд.

Блок А.Н.3. Искорежить поле MobileNumber так, чтобы каше не поняла, что по нему можно использовать индекс
Типа
where string(MobileNumber) like '%..'

Корежила- string(MobileNumber), LOWER(MobileNumber)- То же самое.


Пожалуй, самое простое - третий вариант.[/quot]
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38288998
Фотография DAiMor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Вот если бы вы выложили исходный код задействованных классов, без методов, только значимое (свойства, индексы)
и и подправили так чтобы мы могли сгенерировать тестовые данные и тогда кто нибудь здесь бы смог бы подобрать наиболее оптимальный вариант запроса и схемы данных
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289013
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
servitНо хотелось бы сперва узнать: Вы мои и других участников варианты пробовали? Потому что я до сих пор вижу у Вас like '%'.
Да, пробовала.
MobileNumber IS NOT NULL works like a charm- 2 seconds!
Только я что-то туплю- где мне это условие ставить, что textbox поле если пустое, то все номера выбирать
Код: sql
1.
MobileNumber IS NOT NULL - ?

, а есле что-то там ввели, то это и передавать- 3538 например
Код: sql
1.
MobileNumber LIKE '3538%' - ?

Тогда это уже два запроса?
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289019
Блок А.Н.
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichka,

попробуйте выполнить мои рекомендации.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289034
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
servitЯ хотел бы увидеть планы и результаты моих трёх вариантов: подзапрос


The results of executing the SQL query are shown below:
Last update: 2013-06-06 17:05:14.473
SQLCODE: 100 Row count: 565 Performance: 61.659 seconds 48494 global references

The execution plan is displayed below:
Query Text

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
SELECT DISTINCT TOP 5000 * FROM %NOTOPOPT( 
 SELECT 
 ResponseArchive.ResponseID, ResponseArchive.MobileNumber AS MobileNo, 
 ResponseText AS Message 
 ,ResponseDate 
 FROM Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseDate >= '2013-03-01' 
 AND MessageArchive.DateArchived BETWEEN '2013-03-01' AND '2013-03-31' 
 ) WHERE MobileNo LIKE '%' 
 order by MobileNo, ResponseDate 



Query Plan
Relative cost = 17836 ◾Call module B, which populates temp-file A.

◾Read temp-file A, looping on MobileNumber, ResponseDate, and ID.
◾For each row:

Read master map Client.ResponseArchive.Primary, using the given idkey value.
Read index map Client.MessageArchive.MobileNumber, using the given MobileNumber, and looping on ID.
For each row:
Read master map Client.MessageArchive.Primary, using the given idkey value.
Output the row.

module B
◾Read index map Client.ResponseArchive.ResponseDate, looping on ResponseDate (with a range condition), MobileNumber (with a %STARTSWITH range condition), and ResponseID.

◾For each row:
Add a row to temp-file A, subscripted by MobileNumber, ResponseDate, and ID,
with no node data.





servit is not null


The results of executing the SQL query are shown below:
Last update: 2013-06-06 17:10:08.511
SQLCODE: 100 Row count: 565 Performance: 2.059 seconds 265349 global references

The execution plan is displayed below:
Query Text

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
SELECT DISTINCT TOP 5000 
 ResponseArchive.ResponseID, ResponseArchive.MobileNumber AS MobileNo, 
 ResponseArchive.ResponseText AS Message, 
 ResponseArchive.ResponseDate 
 FROM 
 %NOTOPOPT 
 Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseArchive.ResponseDate >= '2013-03-01' 
 AND MessageArchive.DateArchived BETWEEN '2013-03-01' AND '2013-03-31' 
 AND ResponseArchive.MobileNumber IS NOT NULL 
 order by ResponseArchive.MobileNumber, ResponseArchive.ResponseDate desc 



Query Plan
Relative cost = 2593337 ◾Call module C, which populates temp-file A.

◾Read temp-file A, looping on MobileNumber, ResponseDate, and a counter.
◾For each row:

Output the row.

module C
◾Call module B, which populates temp-file B.
◾Read temp-file B, looping on ID.
◾For each row:

Read master map Client.MessageArchive.Primary, using the given idkey value.
Call module D, which populates temp-file C.
Read temp-file C, using the given MobileNumber, and looping on ID.
For each row:
Read master map Client.ResponseArchive.Primary, using the given idkey value.
Check distinct values for MobileNumber and ResponseID using a temp-file.
For each distinct row:
Add a row to temp-file A, subscripted by MobileNumber, ResponseDate, and a counter,
with node data of ResponseID, ResponseText, [value], and [value].

module B
◾Read index map Client.MessageArchive.DateArchived, looping on DateArchived (with a range condition) and ID.

◾For each row:
Add a row to temp-file B, subscripted by ID,
with no node data.

module D
◾Read index map Client.ResponseArchive.ResponseDate, looping on ResponseDate (with a range condition), MobileNumber, and ResponseID.

◾For each row:
Add a row to temp-file C, subscripted by MobileNumber and ID,
with no node data.




servit [


The results of executing the SQL query are shown below:
Last update: 2013-06-06 17:12:57.039
SQLCODE: 100 Row count: 565 Performance: 63.781 seconds 48496 global references

The execution plan is displayed below:

Query Text

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
SELECT DISTINCT TOP 5000 
 ResponseArchive.ResponseID, ResponseArchive.MobileNumber AS MobileNo, 
 ResponseArchive.ResponseText AS Message, 
 ResponseArchive.ResponseDate 
 FROM 
 %NOTOPOPT 
 Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseArchive.ResponseDate >= '2013-03-01' 
 AND MessageArchive.DateArchived BETWEEN '2013-03-01' AND '2013-03-31' 
 AND ResponseArchive.MobileNumber [ '353' 
 order by ResponseArchive.MobileNumber, ResponseArchive.ResponseDate desc 



Query Plan
Relative cost = 19776 ◾Call module B, which populates temp-file A.

◾Read temp-file A, looping on MobileNumber, ResponseDate, and ID.

◾For each row:
Read master map Client.ResponseArchive.Primary, using the given idkey value.
Read index map Client.MessageArchive.MobileNumber, using the given MobileNumber, and looping on ID.
For each row:
Read master map Client.MessageArchive.Primary, using the given idkey value.
Output the row.

module B
◾Read index map Client.ResponseArchive.ResponseDate, looping on ResponseDate (with a range condition), MobileNumber, and ResponseID.

◾For each row:
Add a row to temp-file A, subscripted by MobileNumber, ResponseDate, and ID,
with no node data.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289039
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Блок А.Н.vichka,
попробуйте выполнить мои рекомендации.

Блок А.Н.,
Пробовала- смотрите выше, описала...
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289043
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
DAiMorВот если бы вы выложили исходный код задействованных классов, без методов, только значимое (свойства, индексы)
...
Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
Class Client.ResponseArchive Extends (%Library.Persistent, %Library.Populate) [ ClassType = persistent, Not ProcedureBlock, StorageStrategy = "" ]
{

/// Response ID
Property ResponseID As %String(MAXLEN = 10, MINLEN = 0) [ Required ];

Index ResponseID On ResponseID;

/// Mobile Number
Property MobileNumber As %String(COLLATION = "EXACT", MAXLEN = 20, MINLEN = 0);

Index MobileNumber On MobileNumber;

/// Response Date
Property ResponseDate As %Date [ Required ];

Index ResponseDate On ResponseDate;

/// Response Time
Property ResponseTime As %Time [ Required ];

/// Response Text
Property ResponseText As %String(MAXLEN = 250, MINLEN = 0) [ Required ];

/// Response Comment
Property ResponseComment As %String(MAXLEN = 250, MINLEN = 0);

/// Mobile Number Operator ID
Property MNOID As %String(MAXLEN = 7, MINLEN = 0) [ Required ];

/// Response Actioned Flag
Property ResponseActionedFlag As %Boolean;

/// Response Review
Property ReviewedDate As %Date;

Property ReviewedTime As %Time;

Property ReviewedBy As %String;

Index Primary On (MobileNumber, ResponseID) [ IdKey, PrimaryKey ];

...
}



Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
Class Client.MessageArchive Extends (%Library.Persistent, %Library.Populate) [ ClassType = persistent, Not ProcedureBlock, StorageStrategy = "" ]
{

/// Message ID
Property MessageID As %Integer(MAXVAL = 2000000000, MINVAL = 0) [ Required ];

Index RequestResponseID On RequestResponseID;

/// Message Text
Property MessageText As %String(MAXLEN = "") [ Required ];

/// Message Type
Property MessageType As %String(MAXLEN = 10, MINLEN = 0) [ Required ];

/// Mobile Number
Property MobileNumber As %String(COLLATION = "EXACT", MAXLEN = 20, MINLEN = 0);

Index MobileNumber On MobileNumber;

/// Date Message Sent
Property DateSent As %Date;

Index DateSent On DateSent;

/// Time Message Sent
Property TimeSent As %Time;

/// Template ID used
Property TemplateIDUsed As %String(MAXLEN = 20, MINLEN = 0) [ Required ];

Index TemplateIDUsed On TemplateIDUsed;

/// Date Message Queued
Property DateQueued As %Date [ Required ];

Index DateQueued On DateQueued;

/// Time Message Queued
Property TimeQueued As %Time [ Required ];

/// Queue ID
Property QueueID As %String(MAXLEN = 10, MINLEN = 0);

/// Issued By
Property IssuedBy As %String(COLLATION = "Exact", MAXLEN = 50, MINLEN = 0) [ Required ];

Index IssuedBy On IssuedBy;

/// Cancelled By
Property CancelledBy As %String(MAXLEN = 50, MINLEN = 0);

Index CancelledBy On CancelledBy;

/// Email Address
Property EmailAddress As %String(MAXLEN = 100, MINLEN = 0);

/// Request Response ID
Property RequestResponseID As %String(MAXLEN = 10, MINLEN = 0) [ Required ];

/// Request Status Code
Property RequestStatusCode As %String(MAXLEN = 5, MINLEN = 0) [ Required ];

Index RequestStatusCode On RequestStatusCode;

/// Response Error Text
Property RequestErrorText As %String(MAXLEN = 250, MINLEN = 0);

Index RequestErrorText On RequestErrorText;

/// Interface ID
Property InterfaceID As %String(MAXLEN = 30, MINLEN = 0);

Index InterfaceID On InterfaceID;

/// Customer Reference
Property CustomerReference As %String(MAXLEN = 100, MINLEN = 0);

/// Batch Reference
Property BatchReference As %String(COLLATION = "Exact", MAXLEN = 200, MINLEN = 0);

Index BatchReference On BatchReference;

/// Supplied Mobile Number
Property SuppliedMobileNumber As %String(MAXLEN = 30, MINLEN = 0);

/// Date Message was archived
Property DateArchived As %Date;

Index DateArchived On DateArchived;

/// Time Message was archived
Property TimeArchived As %Time;

/// Send message at date
Property SendOnDate As %Date;

/// Send message at time
Property SendAtTime As %Time;

/// Message Expiry Date
Property ExpiryDate As %Date;

/// Message Expiry Time
Property ExpiryTime As %Time;

/// Index DateArchived On DateArchived;
Index Primary On MessageID [ IdKey, PrimaryKey ];

/// Comments are to handle the PIN (Patient Internal Number)
Property Comments As %String(MAXLEN = 100, MINLEN = 0);

/// SMS Provider record which SMS Provider was used to send the message
Property SMSProvider As %String(MAXLEN = 30, MINLEN = 0);

...

}
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289058
servit
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichkaДа, пробовала.
MobileNumber IS NOT NULL works like a charm- 2 seconds!Спасибо.
vichkaТолько я что-то туплю- где мне это условие ставить, что textbox поле если пустое, то все номера выбирать
<...>
, а есле что-то там ввели, то это и передавать- 3538 например
<...>
Тогда это уже два запроса?Нет, можно в одном запросе:
Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
SELECT DISTINCT TOP 5000 
 ResponseArchive.ResponseID, ResponseArchive.MobileNumber AS MobileNo, 
 ResponseArchive.ResponseText AS Message, 
 ResponseArchive.ResponseDate 
 FROM 
 %NOTOPOPT 
 Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseArchive.ResponseDate >= '2013-03-01' 
 AND MessageArchive.DateArchived BETWEEN '2013-03-01' AND '2013-03-31' 
 AND ((входнойпараметр IS NULL AND ResponseArchive.MobileNumber IS NOT NULL) or (входнойпараметр IS NOT NULL AND ResponseArchive.MobileNumber LIKE '%'||входнойпараметр||'%'))
 order by ResponseArchive.MobileNumber, ResponseArchive.ResponseDate desc
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289084
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
servitНет, можно в одном запросе

<...>


Должна сказать, что этих LIKE '%' очень много во всех запросах.

Например, оригинальный запрос, над которым я бьюсь:

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
Query rdSPResponses(StartDate As %Date, EndDate As %Date, MobileNumber As %String, BatchReference As %String, Department As %String, UserID As %String, Template As %String, MaxRec As %Integer) As %SQLQuery [ SqlProc ]
{
	
SELECT distinct top :MaxRec  
ResponseID, ResponseArchive.MobileNumber as MobileNumber,
ResponseDate,ResponseTime,
ResponseText,ResponseActionedFlag   
,{fn concat ( {fn concat (ContactSurname,', ')}, ContactName)} as FullName
,ReviewedBy
FROM %NOTOPOPT ResponseArchive inner join MessageArchive
on ResponseArchive.MobileNumber = MessageArchive.MobileNumber
 left outer join ContactDetails on ResponseArchive.MobileNumber = ContactDetails.ContactMobileNumber
 left outer join Users on MessageArchive.IssuedBy = Users.UserID and ResponseArchive.MobileNumber = MessageArchive.MobileNumber
  Where (DateArchived >= :StartDate) and 
  (DateArchived <= :EndDate) and 
  (ResponseDate >= :StartDate) and 
  (ResponseArchive.MobileNumber Like :MobileNumber) 
  and BatchReference Like :BatchReference
and Department Like :Department
  and IssuedBy Like :UserID
  and  RequestStatusCode =0
  and TemplateIDUsed like :Template
  order by ResponseArchive.MobileNumber, ResponseDate desc, ResponseTime desc
}



Как мне его заменить, используя IS NOT NULL?
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289109
Фотография DAiMor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Тут не сказали про хранение данных в индексе, что тоже очень хорошо влияет на скорость
например
Код: sql
1.
Index ResponseDate On ResponseDate [ Data = (MobileNumber, ResponseID) ];
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38289197
servit
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichkaДа, TUNE TABLE все время делаю. Это называется СТАТИСТИКА по-русски? Я даже не знала.Да я тоже не местный, но судя по ...


vichkaДолжна сказать, что этих LIKE '%' очень много во всех запросах.
Не проблема заменить их все, там где это нужно. Например:

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
SELECT distinct top :MaxRec  
ResponseID, ResponseArchive.MobileNumber as MobileNumber,
ResponseDate,ResponseTime,
ResponseText,ResponseActionedFlag   
,{fn concat ( {fn concat (ContactSurname,', ')}, ContactName)} as FullName
,ReviewedBy
FROM %NOTOPOPT ResponseArchive inner join MessageArchive
on ResponseArchive.MobileNumber = MessageArchive.MobileNumber
 left outer join ContactDetails on ResponseArchive.MobileNumber = ContactDetails.ContactMobileNumber
 left outer join Users on MessageArchive.IssuedBy = Users.UserID and ResponseArchive.MobileNumber = MessageArchive.MobileNumber
  Where DateArchived between :StartDate and :EndDate
  and ResponseDate >= :StartDate
  and ((:MobileNumber in not null and ResponseArchive.MobileNumber Like :MobileNumber) or (:MobileNumber is null and ResponseArchive.MobileNumber is not null)) 
  and BatchReference Like :BatchReference
  and Department Like :Department
  and IssuedBy Like :UserID
  and  RequestStatusCode =0
  and TemplateIDUsed like :Template
  order by ResponseArchive.MobileNumber, ResponseDate desc, ResponseTime desc


Хорошо бы, чтобы все поля, по которым ведётся поиск или соединение, были проиндексированы. Возможно, здесь на некоторые из них не помешали бы bitmap-индексы.
Но пока попробуйте просто запрос поменять (и с/без %NOTOPOPT).
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290069
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
servitА у Вас в Ирландии как это называют?


А так и говорят- DO Tune the table. OR: DID you Tune the Table?


servitХорошо бы, чтобы все поля, по которым ведётся поиск или соединение, были проиндексированы.

Да, я их все проиндексировала (см. выше начало классов с полями и индексами)

servitНо пока попробуйте просто запрос поменять (и с/без %NOTOPOPT).


Попробовала. Все равно же приходится ставить '%':

%NOTOPOPT:

The results of executing the SQL query are shown below:
Last update: 2013-06-07 09:50:57.582
SQLCODE: 100 Row count: 557 Performance: 11.608 seconds 267469 global references

The execution plan is displayed below:
Query Text:

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
SELECT DISTINCT TOP 5000 
 ResponseArchive.MobileNumber AS MobileNo, 
 ResponseText AS Message, 
 ResponseDate 
 FROM 
 %NOTOPOPT 
 Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseDate >= '2013-03-01' 
 AND DateArchived >= '2013-03-01' 
 AND DateArchived <= '2013-03-31' 
 and (('%' is not null and ResponseArchive.MobileNumber Like '%') or ('%' is null and ResponseArchive.MobileNumber is not null)) 
 order by ResponseDate 




Query Plan
Relative cost = 16822 ◾Read index map Client.ResponseArchive.ResponseDate, looping on ResponseDate (with a range condition), MobileNumber (with a %STARTSWITH range condition), and ResponseID.

◾For each row:
Read master map Client.ResponseArchive.Primary, using the given idkey value.
Read index map Client.MessageArchive.MobileNumber, using the given MobileNumber, and looping on ID.
For each row:
Read master map Client.MessageArchive.Primary, using the given idkey value.
Check distinct values for MobileNumber, %SQLUPPER(ResponseText), and ResponseDate using a temp-file.
For each distinct row:
Output the row.

-------------------------------------
without %NOTOPOPT:


The results of executing the SQL query are shown below:
Last update: 2013-06-07 09:52:40.191
SQLCODE: 100 Row count: 557 Performance: 59.436 seconds 42768 global references

The execution plan is displayed below:

Query Text

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
SELECT DISTINCT TOP 5000 
 ResponseArchive.MobileNumber AS MobileNo, 
 ResponseText AS Message, 
 ResponseDate 
 FROM 
 Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseDate >= '2013-03-01' 
 AND DateArchived >= '2013-03-01' 
 AND DateArchived <= '2013-03-31' 
 and (('%' is not null and ResponseArchive.MobileNumber Like '%') or ('%' is null and ResponseArchive.MobileNumber is not null)) 
 order by ResponseDate 



Query Plan
Relative cost = 5816.2 ◾Read index map Client.ResponseArchive.ResponseDate, looping on ResponseDate (with a range condition), MobileNumber (with a %STARTSWITH range condition), and ResponseID.

◾For each row:

Read master map Client.ResponseArchive.Primary, using the given idkey value.
Read index map Client.MessageArchive.MobileNumber, using the given MobileNumber, and looping on ID.
For each row:
Read master map Client.MessageArchive.Primary, using the given idkey value.
Check distinct values for MobileNumber, %SQLUPPER(ResponseText), and ResponseDate using a temp-file.
For each distinct row:
Output the row.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290133
servit
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichkaПопробовала. Все равно же приходится ставить '%':Передавайте null , если нужно выбрать всё, а не '%'.

Если же '%' зашит в клиенте и это уже не изменить, то немного измените условие:
вместо
Код: sql
1.
and ((:MobileNumber in not null and ResponseArchive.MobileNumber Like :MobileNumber) or (:MobileNumber is null and ResponseArchive.MobileNumber is not null))

поставьте
Код: sql
1.
and ((:MobileNumber!='%' and ResponseArchive.MobileNumber Like :MobileNumber) or (:MobileNumber='%' and ResponseArchive.MobileNumber is not null))
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290220
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
servitЕсли же '%' зашит в клиенте и это уже не изменить...

Я тестирую эти запросы в WinSQL.
Поэтому ставлю '%' , как вызывается из .NET.
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290419
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
[quot servit]
Передавайте null , если нужно выбрать всё, а не '%'.
[quot]

Ура! Получилось! Никак не могла врубиться в этот NULL !

SHOW PLAN:
The results of executing the SQL query are shown below:
Last update: 2013-06-07 11:59:06.554
SQLCODE: 100 Row count: 557 Performance: 1.667 seconds 267469 global references

Query Text

Код: sql
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
SELECT DISTINCT TOP 5000 
 ResponseArchive.MobileNumber AS MobileNo, 
 ResponseText AS Message, 
 ResponseDate 
 FROM 
 %NOTOPOPT 
 Client.ResponseArchive 
 INNER JOIN Client.MessageArchive 
 ON ResponseArchive.MobileNumber = MessageArchive.MobileNumber 
 WHERE ResponseDate >= '2013-03-01' 
 AND DateArchived >= '2013-03-01' 
 AND DateArchived <= '2013-03-31' 
 and ((NULL is not null and ResponseArchive.MobileNumber Like NULL) or (null is null and ResponseArchive.MobileNumber is not null)) 
 order by ResponseDate 



Query Plan
Relative cost = 2540116
◾Call module C, which populates temp-file A.
◾Read temp-file A, looping on ResponseDate and a counter.
◾For each row:
Output the row.

module C
◾Call module B, which populates temp-file B.
◾Read temp-file B, looping on ID.
◾For each row:
Read master map Client.MessageArchive.Primary, using the given idkey value.
Call module D, which populates temp-file C.
Call module E, which populates temp-file D.
Read temp-file D, using the given MobileNumber, and looping on ID.
For each row:
Check distinct values for MobileNumber, %SQLUPPER(ResponseText), and ResponseDate using a temp-file.
For each distinct row:
Add a row to temp-file A, subscripted by ResponseDate and a counter,
with node data of MobileNumber, %SQLUPPER(ResponseText), [value], and [value].

module B
◾Read index map Client.MessageArchive.DateArchived, looping on DateArchived (with a range condition) and ID.
◾For each row:
Add a row to temp-file B, subscripted by ID,
with no node data.

module D
◾Read index map Client.ResponseArchive.ResponseDate, looping on ResponseDate (with a range condition), MobileNumber, and ResponseID.
◾For each row:
Add a row to temp-file C, subscripted by ID,
with no node data.

module E
◾Read temp-file C, looping on ID.
◾For each row:
Read master map Client.ResponseArchive.Primary, using the given idkey value.
Add a row to temp-file D, subscripted by MobileNumber and ID,
with node data of ResponseDate and %SQLUPPER(ResponseText).
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290445
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
DAiMorТут не сказали про хранение данных в индексе, что тоже очень хорошо влияет на скорость
например
Код: sql
1.
Index ResponseDate On ResponseDate [ Data = (MobileNumber, ResponseID) ];



Как это?
Вместо:
Код: sql
1.
Index ResponseDate On ResponseDate ;


вот это:
Код: sql
1.
Index ResponseDate On (MobileNumber, ResponseID);


?
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290459
Фотография DAiMor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
vichkaDAiMorТут не сказали про хранение данных в индексе, что тоже очень хорошо влияет на скорость
например
Код: sql
1.
Index ResponseDate On ResponseDate [ Data = (MobileNumber, ResponseID) ];



Как это?
Вместо:
Код: sql
1.
Index ResponseDate On ResponseDate ;


вот это:
Код: sql
1.
Index ResponseDate On (MobileNumber, ResponseID);


?
Нет именно так как я и написал, это значит что если будут необходимы данные например для выборки или для выполнения дополнительных условий, то для того чтобы он их не искал в другом месте, данные будут сохранены в индекс, они будут не проиндексированы а сохранены вместе с индексом
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290859
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
DAiMor...Нет именно так как я и написал, это значит что если будут необходимы данные например для выборки или для выполнения дополнительных условий, то для того чтобы он их не искал в другом месте, данные будут сохранены в индекс, они будут не проиндексированы а сохранены вместе с индексом

Я попробовала запустить старый запрос с новым индексом- не помогло.
Зато когда заменила MobileNumber с '%' на MobileNumber с NULL , быстродействие значительно возросло!
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290863
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Спасибо всем за подсказки и оеративную помощь!

Отдельное огромное спасибо SERVIT !
WRC отдыхает!
...
Рейтинг: 0 / 0
Помогите оптимизировать SQL запрос
    #38290902
vichka
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
И последний вопрос- как мне заменить остальные , если там значения или выбранные из dropdownlist, a не из textbox как MobileNumber, или же все существующие?

Так, если все записи, то заменить условия типа:
Код: sql
1.
Department Like '%'



на:
Код: sql
1.
((NULL is not null and Department = NULL) or (NULL is null and Department is not null))



---------------------------------
а если что-то выбрано, то вместо:
Код: sql
1.
Department Like 'DepartmentName%'



будет:
Код: sql
1.
(('DepartmentName' is not null and Department = 'DepartmentName') or ('DepartmentName' is null and Department is not null))




Запустила- особой разницы не увидела.
Стоит ли заменять?
...
Рейтинг: 0 / 0
25 сообщений из 62, страница 2 из 3
Форумы / Caché, Ensemble, DeepSee, MiniM, IRIS, GT.M [игнор отключен] [закрыт для гостей] / Помогите оптимизировать SQL запрос
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]