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

问题描述 投票:0回答:1

我有两张表,我想过滤掉表中的行。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 ); """

我的表有几千行,所以执行起来需要很长时间,有什么更好的解决方案吗?

python sql subquery inner-join
1个回答
0
投票

我假设 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 
)

0
投票

为什么不先过滤掉书表,然后把这个过滤后的小表和类表连接起来?

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

0
投票

你可以用IN,或者EXISTS或者做一个JOIN来写这个查询.我建议你尝试JOIN.这取决于实际的DBMS,查询优化器和你的数据分布,是否存在索引等。这取决于实际的DBMS,查询优化器和你的数据分布,是否存在索引等,但根据我的经验,如果可以使用INER join,这种结构工作得更快.但同样重要的是,你要确保在你加入的列上有索引(过滤),所以这两个。

class.order_id = books.orderid.

但也。

books.name和books.lastname

也许在姓氏上建立索引就够了,那么就必须扫描相同姓氏的行来寻找匹配的名字。

你用的是哪个DBMS?通常有一种方法可以检查查询执行计划,你可以看到哪些部分很慢。比如说 "EXPLAIN SELECT ..." 在MySQL中。

Artur

© www.soinside.com 2019 - 2024. All rights reserved.