在不同的表中有一个“orderby”列更好吗?

ndasle7k  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(202)

我有下表存储图像:

id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ... 
12        img_2.png        2            3          text ...        text ... 
22        img_3.png        1            1          text ...        text ... 
....
..
Around 2,000,000 rows

假设我需要为客户获取图像 1 按优先顺序排列。我可以执行一个简单的查询,比如 select image from images order by priority .
由于涉及到大量的行,所以最好有一个单独的表来存储图像id和优先级,如下所示

id        image_id       priority
1            1              1
2            12             2
3            22             1

为了得到相同的结果,我将使用一个简单的连接: select a.image from priorities b join images a on a.id = b.image_id order by b.priority 两个中哪一个更快?

swvgeqrz

swvgeqrz1#

为了更快地执行查询,最好使用一个非规范化的表,将所有数据放在一个地方。
连接会导致执行时间变慢,因此只有在希望有更好的模式并减少数据冗余时,才创建两个表。

8ljdwjyq

8ljdwjyq2#

请使用下面的查询,没有必要有一个以上的表。您可以创建适当的索引并使用相同的表

select image from images order by id, priority;
xurqigkl

xurqigkl3#

如果你需要照片 client = 1 ,则查询将是:

select i.image
from images i
where i.client_id = 1
order by i.priority;

此查询可以利用上的索引 images(client_id, priority) --不需要显式排序。
您需要的查询是:

select i.image
from priorities p join
     images i
     on p.id = i.image_id
where i.client_id = 1
order by bp.priority;

在这个查询中 where 使用一个表中的列和 select 从另一张table。这是很难优化,所以我猜你不能绕过做排序。
从性能的Angular 来看,最好将数据放在一个表中,并使用正确的索引。

相关问题