临时表的替代方案

时间:2012-11-13 20:15:43

标签: mysql temp-tables

我需要什么(并使用临时表或视图):

numcasos  valcount1  valcount2  
--------  ---------  -----------
       0          2            1
       1          1            2
       2     (NULL)       (NULL)
       3     (NULL)            1
       4          1       (NULL)
       5     (NULL)       (NULL)
       6     (NULL)       (NULL)
       7     (NULL)       (NULL)
       8     (NULL)       (NULL)
       9     (NULL)       (NULL)
      10     (NULL)       (NULL)

这是一个例子,因为我需要300多个valcounts。 MySQL的:

CREATE TEMPORARY TABLE sumnum1
SELECT numos.num1 AS num1,
 COUNT(*)   AS valcount1      
FROM `numos` 
GROUP BY numos.num1  ; 

CREATE TEMPORARY TABLE sumnum2
SELECT numos.num2 AS num2,
 COUNT(*)   AS valcount2      
FROM `numos` 
GROUP BY numos.num2  ; 



SELECT casos.`numcasos` AS numcasos, 
sumnum1.valcount1 AS valcount1,
sumnum2.valcount2 AS valcount2

FROM ( casos
LEFT JOIN sumnum1
ON (casos.`numcasos`= sumnum1.num1)
LEFT JOIN sumnum2
ON (casos.numcasos = sumnum2.num2))

我想要的是用子查询获得相同的结果,但我收到错误消息:

Subquery returns more than 1 row

在MySQL可以吗?

1 个答案:

答案 0 :(得分:7)

尝试类似

的内容
SELECT casos.numcasos AS numcasos, 
sumnum1.valcount1 AS valcount1,
sumnum2.valcount2 AS valcount2
FROM casos
LEFT JOIN
(
    SELECT numos.num1 AS num1, COUNT(*) AS valcount1
    FROM numos GROUP BY numos.num1 
)sumnum1  ON (casos.`numcasos`= sumnum1.num1)
LEFT JOIN 
(
   SELECT numos.num2 AS num2, COUNT(*) AS valcount2
   FROM numos GROUP BY numos.num2  
)sumnum2 ON (casos.numcasos = sumnum2.num2))