MySQL:使用一个查询的结果作为另一个查询的输入

时间:2013-03-06 22:32:30

标签: mysql join subquery resultset

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

我知道我可以轻松编写一个程序来填充表格,但我想知道是否有办法生成相同的结果集而不用外部处理。

例如,结果集来自:

SELECT DISTINCT city, state FROM lkp_city_state AS locations;

现在,对于这些城市/州的组合,我想计算其中的Ferarris和Lamborghinis的数量。

的内容
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

这可能吗?

2 个答案:

答案 0 :(得分: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,

答案 1 :(得分: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 testing