SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
Оптимизация SQL
       Михаил Гуренков




     17 октября 2008 г. Клуб Маинфо.ру
Упрощение схемы данных
Неявное соединение → ...

select *
from
   xCompaniesToCategories cc, xCompanies c,
   xCompanyProperties p, xPersons pe, #addresses aj,
   #addresses af, xCompaniesToPersons ctp, xContracts
co
where
   p.id_Company = c.id and pe.id = id_Chief and
   aj.id = id_DejuroAddress and af.id = id_DefactoAddress
   and ctp.id_Company = c.id and ctp.id_Person = pe.id
and
   co.id_Company = c.id and c.id = cc.id_Company and
   id_Category = 30 and p.id_Company = c.id
... → Явное соединение

select *
from xCompanies c
   join xCompaniesToCategories cc on c.id = cc.id_Company
   join xCompanyProperties p on p.id_Company = c.id
   join xPersons pe on pe.id = id_Chief
   join #addresses aj on aj.id = id_DejuroAddress
   join #addresses af on af.id = id_DefactoAddress
   join xCompaniesToPersons ctp
      on ctp.id_Company = c.id and ctp.id_Person = pe.id
   join xContracts co on co.id_Company = c.id
where
   id_Category = 30
Типовые запросы → представления

select *
from OrderServices s
   join Orders o on s.id_Order = o.id
where id_Company = 1234

                 ↓
select * from vOrderServices where id_Company = 1234
Инкапсуляция запросов
create view vOrderServiceHistory as
select os1.*, os1.AffectedDate DateOn, os2.AffectedDate DateOff,
os2.id_Order id_OrderOff from vOrderServices os1
  left join vOrderServices os2 on (os1.id_Company = os2.
id_Company and os1.id_Resource = os2.id_Resource and os2.
ServiceHash = os1.ServiceHash and os2.Rang < os1.Rang and
os2.Action = -1) and
     not exists (select * from vOrderServices os3 where os1.
id_Company = os3.id_Company and os1.id_Resource = os3.
id_Resource and os3.ServiceHash = os1.ServiceHash and os3.
Rang > os2.Rang and os3.Rang < os1.Rang and os3.Action = -1)

where os1.OrderTypeAction = 1
Рефакторинг базы данных
Использование индексов
Оптимизаторы

Rule-based (RBO)
Cost-based (CBO)
Денормализация данных
Составные тэги


              ЦСКА (баскетболл, муж)
                        ↓
   «ЦСКА (баскетболл, муж)», «баскетболл», «муж»
SQL и процедурный стиль
   программирования
Новости по теме

select news.* from news
  join (
     select distinct n.id from news n
     join taggings t1 on t1.news_id = ?
     join taggings t2 on t2.news_id = ? and t1.id_tag > t2.id_tag
     join taggings r1 on t1.tag_id = r1.tag_id and r1.news_id = n.id
     join taggings r2 on t2.tag_id = r2.tag_id and r2.news_id = n.id
  ) related on news.id = related.id
where news.id != ?
order by publishing_date desc
Публикация прайс-листа
Функции

select
   id, dbo.GetServiceAbonPrice(id, getdate()) as AbonPrice
from vOrderServices

select id, abon.Price
from vOrderServices os
   join dbo.GetAbonPrices() as abon
      on abon.ServiceHash = os.ServiceHash
        and abon.id_Company = os.id_Company
В заключение
Главные мысли

1. Забота о схеме данных
2. Правильное использование индексов
3. SQL — не язык программирования
Мартин Грабер
«SQL»
Джо Селко
«SQL для профессионалов»
Скотт Эмблер,
 Прамод Садаладж
«Рефакторинг баз данных»
Ссылки

1.   www.sql.ru
2.   msdn.microsoft.com
3.   dev.mysql.com/doc/refman/5.1/en/optimization.html
4.   community.livejournal.com/ru_mysql/
5.   ...
www.dreamspark.ru
Контакты


           michael@gurenkov.net
               www.gurenkov.net
SQL has been optimized :)

Más contenido relacionado

Más de Constantin Kichinsky

Шаблоны проектирования 2
Шаблоны проектирования 2Шаблоны проектирования 2
Шаблоны проектирования 2Constantin Kichinsky
 
Шаблоны проектирования 1
Шаблоны проектирования 1Шаблоны проектирования 1
Шаблоны проектирования 1Constantin Kichinsky
 
Создание новых объектов
Создание новых объектовСоздание новых объектов
Создание новых объектовConstantin Kichinsky
 
jQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScriptjQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScriptConstantin Kichinsky
 
Django – фреймворк, который работает
Django – фреймворк, который работаетDjango – фреймворк, который работает
Django – фреймворк, который работаетConstantin Kichinsky
 
Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!Constantin Kichinsky
 
Управление проектами
Управление проектамиУправление проектами
Управление проектамиConstantin Kichinsky
 
Код как низкоуровневая документация
Код как низкоуровневая документацияКод как низкоуровневая документация
Код как низкоуровневая документацияConstantin Kichinsky
 
Ajax и будущее Java Script
Ajax и будущее Java ScriptAjax и будущее Java Script
Ajax и будущее Java ScriptConstantin Kichinsky
 
Cтиль программирования
Cтиль программированияCтиль программирования
Cтиль программированияConstantin Kichinsky
 

Más de Constantin Kichinsky (20)

Шаблоны проектирования 2
Шаблоны проектирования 2Шаблоны проектирования 2
Шаблоны проектирования 2
 
Шаблоны проектирования 1
Шаблоны проектирования 1Шаблоны проектирования 1
Шаблоны проектирования 1
 
Обработка ошибок
Обработка ошибокОбработка ошибок
Обработка ошибок
 
Создание новых объектов
Создание новых объектовСоздание новых объектов
Создание новых объектов
 
Декомпозиция
ДекомпозицияДекомпозиция
Декомпозиция
 
Design Lecture
Design LectureDesign Lecture
Design Lecture
 
jQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScriptjQuery: быстрая разработка веб-интерфейсов на JavaScript
jQuery: быстрая разработка веб-интерфейсов на JavaScript
 
Django – фреймворк, который работает
Django – фреймворк, который работаетDjango – фреймворк, который работает
Django – фреймворк, который работает
 
Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!Ruby On Rails: Web-разработка по-другому!
Ruby On Rails: Web-разработка по-другому!
 
Silverlight 2
Silverlight 2Silverlight 2
Silverlight 2
 
Управление проектами
Управление проектамиУправление проектами
Управление проектами
 
Silverlight 2
Silverlight 2Silverlight 2
Silverlight 2
 
Код как низкоуровневая документация
Код как низкоуровневая документацияКод как низкоуровневая документация
Код как низкоуровневая документация
 
Imagine Cup
Imagine CupImagine Cup
Imagine Cup
 
Ajax и будущее Java Script
Ajax и будущее Java ScriptAjax и будущее Java Script
Ajax и будущее Java Script
 
RIA & Silverlight
RIA & SilverlightRIA & Silverlight
RIA & Silverlight
 
C# 3.0
C# 3.0C# 3.0
C# 3.0
 
Design Matters
Design MattersDesign Matters
Design Matters
 
Net 3.0 & Linq
Net 3.0 & LinqNet 3.0 & Linq
Net 3.0 & Linq
 
Cтиль программирования
Cтиль программированияCтиль программирования
Cтиль программирования
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Оптимизация SQL