我在PHP中有一个类似于:
的数据库查询SELECT * FROM ($myQuery) AS myDerivedTable
JOIN ( SELECT COUNT(*) FROM myDerivedTable WHERE criteriaA ) AS A
JOIN ( SELECT COUNT(*) FROM myDerivedTable WHERE criteriaB ) AS B
JOIN ( SELECT COUNT(*) FROM myDerivedTable WHERE criteriaC ) AS C
...
目前,假设$myQuery
包含以下内容:
SELECT * FROM table1 ORDER BY dateOfSubmition DESC
我只是想一次又一次地使用派生表(myDerivedTable
),而不是每次都计算它!但mySQL报告错误:
#1146 - Table 'myDB.myDerivedTable' doesn't exist
当然它不存在!到myDerivedTable
,我并没有提到数据库中存在的表,而只是对已经计算过的表的引用!!
我怎样才能达到预期的行为?
答案 0 :(得分:0)
这是使用条件聚合获取不同标准计数的另一种方法
SELECT
COUNT(CASE WHEN criteriaA THEN 1 END) AS A
COUNT(CASE WHEN criteriaB THEN 1 END) AS B
COUNT(CASE WHEN criteriaC THEN 1 END) AS C
FROM ($myQuery) AS myDerivedTable
答案 1 :(得分:0)