0

我有 3 个表交易员,city_state,city_present。

我在交易者表中有 400 万行,我的查询至少需要 20 秒。city_present 和城市表中的记录很少。

以下是我的查询。

   

select t.trader_id, t.name, t.city, t.state from ( SELECT distinct c.city, c.state FROM city_present p,city_state c WHERE p.name = 'TEST_TEST' AND c.city = p.city AND c.state = p.state ) cs, trader t where AND t.city = cs.city AND t.state = cs.state AND t.name = 'john test' AND t.is_valid= 1

我有客户索引(城市,州,名称,valid_customer)子查询不到一秒..外部查询大约需要20秒。

有人可以帮我如何减少查询时间。

4

2 回答 2

0

我假设您在 trader.name 上有一个索引,可能还包括 trader.is_valid?

真的需要不同的吗?这真的需要一个内联视图,还是可以是一个常规连接?

于 2013-05-28T18:30:34.873 回答
0

有些事情你可以在不向架构中添加任何内容的情况下尝试:在你的子查询中,你永远不会从 city_present 中选择任何东西,所以你可以把它变成IN/EXISTS

 select t.trader_id, t.name, t.city, t.state from 
 (
 SELECT c.city, c.state
 FROM city_state c
 WHERE EXISTS (
     select null
     from city_present p
     where
     p.name = 'TEST_TEST'  
     AND c.city = p.city  
     AND c.state = p.state)
 ) 
cs, trader t
where 
AND t.city = cs.city
AND t.state = cs.state
AND t.name = 'john test'
AND t.is_valid= 1

然后,同样的事情适用于cs。所以你可以重写为:

select t.trader_id, t.name, t.city, t.state from 
trader t
where 
exists (
    SELECT null
    FROM city_state c
    WHERE EXISTS (
         select null
         from city_present p
         where
         p.name = 'TEST_TEST'  
         AND c.city = p.city  
         AND c.state = p.state)
    AND t.city = c.city
    AND t.state = c.state
) 
AND t.name = 'john test'
AND t.is_valid= 1

您也可以尝试展平子查询:

select t.trader_id, t.name, t.city, t.state from 
trader t
where 
exists (
     SELECT null
     FROM city_present p,city_state c
     WHERE p.name = 'TEST_TEST'  
     AND c.city = p.city  
     AND c.state = p.state  
     AND t.city = c.city
     AND t.state = c.state
) 
AND t.name = 'john test'
AND t.is_valid= 1

从这里,您应该调查索引:

  • trader.name 和/或 trader.id
  • (city_state.city, city_state.state) 和 (city_present.city, city_present.state)
于 2013-05-29T11:27:47.977 回答