MySQL:FROM子句中的子查询

时间:2015-05-29 04:32:23

标签: mysql

我正在尝试创建一个视图,但我一直收到错误说FROM子句中的子查询

需要创建这些

的视图
SELECT EPC_ploc, COUNT(EPC_ploc)
FROM P_HAS_LOC
GROUP BY EPC_ploc
HAVING COUNT(EPC_ploc) =
(   
    SELECT MAX(mycount)
    FROM
    (
        SELECT EPC_ploc, COUNT(EPC_ploc) mycount
        FROM P_HAS_LOC
        GROUP BY EPC_ploc
    ) AS mycountt
)

SELECT Category_ID_h, COUNT(Category_ID_h)
FROM P_HAS_CA GROUP BY Category_ID_h
HAVING COUNT(Category_ID_h) = 
(   
    SELECT MAX(mycount)
    FROM
    (
        SELECT Category_ID_h, COUNT(Category_ID_h) mycount
        FROM P_HAS_CA
        GROUP BY Category_ID_h) AS mycountt
    )
)

1 个答案:

答案 0 :(得分:1)

我认为您需要在查询中重新编写子查询,这会导致所有问题。你应该能够逃脱这个:

SELECT EPC_ploc, COUNT(EPC_ploc)
FROM P_HAS_LOC
GROUP BY EPC_ploc
HAVING COUNT(EPC_ploc) =
(   
    SELECT COUNT(EPC_ploc)
    FROM P_HAS_LOC
    GROUP BY EPC_ploc
    ORDER BY COUNT(EPC_ploc) DESC
    LIMIT 1;
)

SELECT Category_ID_h, COUNT(Category_ID_h)
FROM P_HAS_CA
GROUP BY Category_ID_h
HAVING COUNT(Category_ID_h) = 
(   
    SELECT COUNT(Category_ID_h)
    FROM P_HAS_CA
    GROUP BY Category_ID_h
    ORDER BY COUNT(Category_ID_h)
    LIMIT 1;
)

正如@pala_所提到的,你也可以使用JOIN重写你的查询,但我上面给出的是使用子查询获取所有组的最大值的正确方法。