0

我有一个庞大的数据库,其中某个查询大约需要 7 秒才能返回结果,因为每个查询在其他计算中都会进行多次计数。为了加快速度,我想创建一个已经计算和存储这些计数的新查找表。

我知道我可以很容易地编写一个程序来填充表格,但我想知道是否有一种方法可以在没有外部处理的情况下生成相同的结果集。

例如,结果集来自:

SELECT DISTINCT city, state FROM lkp_city_state AS locations;

现在,对于这些城市/州组合中的每一个,我想计算其中的法拉利和兰博基尼的数量。类似的东西

SELECT COUNT(*) as num_ferarris FROM cars WHERE manufacturer = 'ferarri' AND city = locations.city AND state = locations.state
    JOIN
SELECT COUNT(*) as num_lambos FROM cars WHERE manufacturer = 'lamborghini' AND city = locations.city AND state = locations.state`

理想的结果集列将类似于:

city | state | num_ferarris | num_lambos

这可能吗?

4

2 回答 2

0

您可以在一个查询中直接加入您的列表

SELECT 
      locations.city,
      locations.state,
      cars.manufacturer,
      COUNT(*)
   FROM cars 
      JOIN lkp_city_state AS locations;
         on cars.city = locations.city
        and cars.state = locations.state
   WHERE 
         cars.manufacturer = 'ferarri' 
      OR cars.manufacturer = 'lamborghini'
   GROUP BY
      locations.city,
      locations.state,
      cars.manufacturer

如果您希望它在一行中,您可以旋转结果

SELECT 
      locations.city,
      locations.state,
      sum( case when cars.manufacturer = 'ferarri' then 1 else 0 end ) as Num_Ferarri,
      sum( case when cars.manufacturer = 'lamborghini' then 1 else 0 end ) as Num_Lambos
   FROM cars 
      JOIN lkp_city_state AS locations;
         on cars.city = locations.city
        and cars.state = locations.state
   WHERE 
         cars.manufacturer = 'ferarri' 
      OR cars.manufacturer = 'lamborghini';
       GROUP BY
          locations.city,
          locations.state,
于 2013-03-06T22:44:15.907 回答
0

首先,考虑使用indexes. 我过去没有使用它们,但最近证实它们在加速查询方面做得非常好。

其次,我认为这样的事情可以奏效:

SELECT * FROM
(    SELECT 
      c.city, c.state, COUNT(*) as num_lambo
    FROM cars AS c
    LEFT JOIN locations
      ON  locations.city = c.city AND locations.state = c.state
    WHERE manufacturer = 'lambo' )A

JOIN

(    SELECT 
      c.city, c.state, COUNT(*) as num_ferr
    FROM cars AS c
    LEFT JOIN locations
      ON  locations.city = c.city AND locations.state = c.state
    WHERE manufacturer = 'ferrari' )B

SQL Fiddle 测试

于 2013-03-06T22:50:03.090 回答