0

我有以下三个查询

SELECT COUNT(*) as cached_type_a, DATE(datetime) as datetime
    FROM requests
    WHERE cached = 'a'
    GROUP BY DAY(datetime);

SELECT COUNT(*) as cached_type_b, DATE(datetime) as datetime
    FROM requests
    WHERE cached = 'b'
    GROUP BY DAY(datetime);

SELECT COUNT(*) as cached_type_c, DATE(datetime) as datetime
    FROM requests
    WHERE cached = 'c'
    GROUP BY DAY(datetime);

是否可以将它们组合成一个包含 4 列的查询

cached_type_a, cached_type_b, cached_type_c, datetime?

4

2 回答 2

1

如果你只有三个可能的值cache,你可以使用这个,

SELECT DATE(datetime) as datetime,
        SUM(CASE WHEN cached = 'a' THEN 1 ELSE 0 END) cached_a,
        SUM(CASE WHEN cached = 'b' THEN 1 ELSE 0 END) cached_b,
        SUM(CASE WHEN cached = 'c' THEN 1 ELSE 0 END) cached_c
FROM requests
GROUP BY DAY(datetime)

否则,如果您有多个缓存,则可以使用Prepared Statement

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN cached =  ''',
      cached,
      ''' then 1 ELSE 0 end) AS ',
      CONCAT('cached_',cached)
    )
  ) INTO @sql
FROM requests;

SET @sql = CONCAT('SELECT DATE(datetime) as datetime, ', @sql, ' 
                   FROM requests 
                   GROUP BY DAY(datetime)');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2012-10-26T02:54:14.807 回答
0
 SELECT COUNT(a.datetime) as cached_type_a,
        COUNT(b.datetime) as cached_type_b,
        COUNT(c.datetime) as cached_type_c,
        DATE(a.datetime) as datetime
 FROM requests a, 
      requests b,
      requests c,  
 WHERE a.cached = 'a' 
   and b.cached = 'b'
   and c.cached = 'c'
 GROUP BY DAY(a.datetime), DAY(b.datetime), DAY(c.datetime);
于 2012-10-26T02:55:50.007 回答