使用子查询结果进行内部连接

pjngdqdw  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(380)

我有两张table。我想从表中筛选出行 class 然后将过滤后的表与 books 比较此新表的两列( orderid 从类表和 order_id 从图书表)。每当这两列匹配时,我都要选择该行。我试过这个

query = """ select col1 , col2 , col3 from class 
INNER JOIN books
ON class.order_id = books.orderid 
IN (SELECT orderid from books where name=%s and lastname=%s ); """

我的表有数千行,所以执行起来需要很长时间。有没有更好的解决办法?

ghhaqwfi

ghhaqwfi1#

我想 col1, col2, col3 来自餐桌 calss 那你可以用 exists ```
select col1 , col2 , col3
from class c
WHERE exists
(
SELECT
orderid
from books b
where c.order_id = b.orderid
and name=%s
and lastname=%s
)

另一个选择是 `orderId` 在子查询中

select col1 , col2 , col3
from class c
INNER JOIN (SELECT orderid from books where name=%s and lastname=%s) b
ON c.order_id = b.orderid

否则,可以在缺少的地方使用原始查询 `where` ```
select col1 , col2 , col3 
from class 
INNER JOIN books
ON class.order_id = books.orderid 
WHERE orderid IN (
  SELECT orderid from books where name=%s and lastname=%s 
)
1szpjjfi

1szpjjfi2#

为什么不先过滤掉book表,然后将这个较小的过滤表与class表连接起来呢?

select col1 , col2 , col3 
from class c
inner join (select * from book where where name=%s and lastname=%s) b
on c.order_id = b.orderid
68bkxrlz

68bkxrlz3#

您可以使用in编写此查询,也可以使用exists或生成join。我建议你试试加入。它取决于实际的dbms、查询优化器和您的数据分布、索引的存在等,但是根据我的经验,如果可以使用内部连接,那么这种构造的工作速度更快。但同样重要的是,您要确保在连接的列(筛选依据)上有索引,因此这两个:
class.order\u id=图书.orderid
而且:
books.name和books.lastname
也许姓氏上的索引就足够了,那么必须扫描具有相同姓氏的行才能找到匹配的名字。
您正在使用哪些数据库管理系统?通常有一种方法可以检查查询执行计划,您可以看到哪些部分执行缓慢。例如 "EXPLAIN SELECT ..." 在mysql中。
阿图尔

相关问题