A lot of folks when they hear about SQL
features like order by, or limit and
offset, ask the question,
why do that in the database?
I already know how to sort
a list in Python, and
I already know how to do slices.
Why don't I just fetch the data back
to my application code unsorted, and
do the work there?
And it's true that count is
an awful lot like length.
And limit 100 offset ten is an awful lot
like taking a slice from elements
ten to a 110 of the result list.
And order by column is an awful lot
like, sorting by a a key that's
actually kind of complicated, but
there are a couple of big differences.
Speed and space.
The database can generally do these
things a lot faster than Python can.
Especially when you get to
tables with lots of rows or
complicated queues that
join several tables.
And you can easily have
a table with millions of rows,
sorting a million items in
Python can take around a second.
If you're writing a web app, that's
a second that you're user is staring at
their browser,
wondering why your app is so
freaking slow, and
it's taking up memory to do that too.
In contrast, a database can generally
do these operations much faster.
There are a number of tricks you
can use to make it faster still.
The big one is called indexing.
We won't deal with indexing
directly in this course, but
later on there will be some
notes on how to apply it.
In any event, doing restrictions and
aggregations in the database,
instead of in Python,
is a good practice to get in to.
So let's do more of that.
عندما يسمع الكثير من الأشخاص عن سمات SQL
مثل order by أو limit
وoffset، يطرحون السؤال
ما الداعي إلى ذلك في قاعدة البيانات؟
قد يقول أحدهم: أنا أعرف فعلاً كيفية ترتيب
،قائمة في Python
.كما أعرف فعلاً كيفية تحديد الشرائح
لما لا أقوم فقط بإحضار البيانات
،إلى التعليمة البرمجية للتطبيق غير مفروزة
وأقوم بما هو مطلوب هناك؟
من الصحيح أن أمر count
.مثل أمر len من حيث الكم الهائل من النتائج
والأمر limit 100 offset 10 يُرجع عددًا كبيرًا من العناصر
مثل أمر results لتحديد شريحة من العناصر
.10 إلى 110 من قائمة النتائج
والأمر ترتيب حسب العمود يعرض عددًا كبيرًا
مثل، فرز حسب مفتاح
الذي يعتبر معقدًا نوعًا ما، لكن
.يوجد اختلافين كبيرين
.السرعة والمساحة
يمكن لقاعدة البيانات أن تنفذ
.هذه الأوامر بسرعة أكبر بكثير من Python
خاصة عندما تحصل على
جداول بعدد كبير من الصفوف أو
قوائم انتظار معقدة
.ترتبط بجداول مختلفة
كما يمكنك أن تحصل بسهولة على
،جدول مكون من ملايين الصفوف
ويمكن لفرز مليون عنصر
.في Python أن يستغرق ثانية واحدة تقريبًا
إذا كنت تكتب تطبيق ويب، إنها ثانية واحدة
التي ينتظرها المستخدم، بعدها يحدق في
،المستعرض
ويتساءل عن سبب
البطء الشديد لتطبيقك
.إلى جانب إشغاله الذاكرة
على عكس هذا، يمكن لقاعدة البيانات
.إجراء هذه العمليات في وقت أسرع بكثير
إلا أنه يوجد هناك عدد من الحيل
.يمكنك استخدامها لزيادة سرعة أداء هذه العملية
.الحيلة الأهم من بينها يطلق عليها الفهرسة
لن نتناول موضوع الفهرسة
،بشكل مباشر في هذه الدورة التدريبية لكن
سيكون هناك بعض
.الملاحظات حول كيفية تطبيقها
على أي حال، إجراء عمليات تقييد
،وaggregation في قاعدة البيانات
،بدلاً من Python
.إجراء جيد لتناوله
.حسنًا، لنقم بالمزيد من ذلك
Muita gente quando ouve falar nos recursos de SQL
como order by, limit e
offset, pergunta
por que fazer isso no banco de dados?
Já sei como classificar
uma lista no Python e
já sei como fazer fatias.
Por que não buscar apenas os dados não classificados
para o código do meu aplicativo e
fazer o trabalho lá?
E é verdade que count é
muito parecido com length.
E limit 100 offset ten é muito parecido com
usar uma fatia de elementos
dez para 110 da lista de resultados.
E a coluna ordenar por é muito parecida
com classificar por uma chave a. Isso
realmente é um pouco complicado, mas
existem duas grandes diferenças.
Velocidade e espaço.
O banco de dados pode geralmente fazer essas
coisas muito mais rapidamente que o Python.
Especialmente quando você obtém
tabelas com muitas linhas ou
filas complicadas que
unem várias tabelas.
E você pode ter facilmente
uma tabela com milhões de linhas;
classificar milhões de itens no
Python pode levar cerca de um segundo.
Se você estiver escrevendo um aplicativo Web, é
nesse segundo que o seu usuário está encarando o
navegador dele,
pensando em como o seu aplicativo é tão
lento, e
está ocupando memória para fazer isso também.
Em compensação, um banco de dados normalmente
pode fazer essas operações muito mais rapidamente.
Existem diversos truques que você
pode usar para tornar isso ainda mais rápido.
O maior deles se chama indexação.
Não lidaremos diretamente com a indexação
neste curso, mas
depois haverá algumas
observações sobre como aplicá-la.
Em qualquer caso, fazer restrições e
agregações no banco de dados,
em vez de no Python,
é uma boa prática a ser seguida.
Vamos fazer um pouco mais disso.
在听到 order by、limit 以及 Offset 这类 SQL 功能时
很多人都会问一个问题 为什么要在数据库中执行这些操作?
我已经知道怎么在 Python 中对一个列表进行排序了
我也知道怎么返回指定的元素
为什么不干脆将未排序的数据返回给应用代码
然后在那里执行操作呢?
count 返回的结果和 length 一样 多得吓人
limit 100 offset 10 返回的结果太多了
就好像是从结果列表中 选取元素 10 至元素 110 一样
对列进行排序 会返回非常多的结果 就像根据复杂的关键字
进行排序一样 但有几个很大的不同之处
速度和占用空间
数据库在执行这些操作时往往比 Python 快得多
尤其是当你碰到的表格 合并了多个表格
有很多行或者 复杂的列时
你很容易就会得到一个有几百万行的表格
在 Python 中对一百万个项目进行排序 大约耗时一秒左右
如果你写的是一个网页应用 你的用户
盯着浏览器看一秒钟 就会觉得奇怪 为何你的应用
这么慢 而且在加载时还会占用内存
相比之下 数据库执行这些操作时往往快得多
你可使用很多技巧让它更快一些
一个很重要的技巧就是索引
在本课中我们不会直接讨论索引
但之后我们会提到如何使用它
在任何情况下 在数据库 而不是在 Python 中
执行限制和聚合操作都是不错的做法
所以 让我们更多地在数据库中执行这些操作吧