在单个查询中从一个表中选择SUM + COUNT,从另一个表中选择COUNT

时间:2013-12-16 14:19:00

标签: php mysql sql

我想从users表中获取活跃的年龄和总用户数以及来自pictures表的png图片总数。我试过以下但它给了我错误。我如何在单个查询中执行此操作?我正在使用PDO

SELECT
(SELECT SUM(age) AS age_sum,COUNT(*) AS total FROM users where type='active'),
(SELECT COUNT(*) AS pictotal FROM pictures where extension='png')

错误 - >操作数应包含1列

4 个答案:

答案 0 :(得分:3)

选择
 AA.age_sum,AA。总计,BB.pictotal

 (SELECT SUM(年龄)AS age_sum,COUNT(*)AS总数来自用户,其中type ='active')AA,
 (SELECT COUNT(*)AS pictotal FROM pictures ='png')BB

答案 1 :(得分:1)

对于你的任务是一个子选择更好的决定 - 像这样

SELECT SUM(age) AS age_sum,COUNT(*) AS total, (SELECT COUNT(*) FROM pictures where extension='png') AS pictotal FROM users where type='active')

当每个查询返回的列数不相等时,您就无法在一个查询中“合并”两个不同的查询。

答案 2 :(得分:1)

你做到了 这个选择是你的问题返回2列
     (SELECT SUM(年龄)AS age_sum,COUNT(*)AS total

 SELECT SUM(age) AS age_sum,COUNT(*) AS total, 
 (SELECT COUNT(*) FROM pictures where extension='png') AS pictotal
 FROM users where type='active' 

答案 3 :(得分:1)

您可以尝试这样的事情:

SELECT 'AGE_SUM',SUM(age) FROM users where type='active'
UNION
SELECT 'TOTAL',COUNT(*) FROM users where type='active'
UNION
SELECT 'PIC_TOTAL',COUNT(*) FROM pictures where extension='png'