同桌数联盟

时间:2011-11-25 12:00:45

标签: mysql count union

SELECT COUNT(*) as totalHappenings FROM `happenings` WHERE `userId` = ? 
UNION 
SELECT COUNT(*) as xHappenings FROM `happenings` WHERE `userId` = ? AND `destinationObjectType` = \'2\' 
UNION 
SELECT COUNT(*) as yHappenings FROM `happenings` WHERE `userId` = ? AND `destinationObjectType` = \'1\'

由于它是同一个表,我不想通过3次userId参数如何才能解决这个问题?

3 个答案:

答案 0 :(得分:1)

您可以使用select子句中的if语句执行此操作:

  SELECT
    COUNT(userId) as totalHappenings, 
    SUM(IF(`destinationObjectType`='2',1,0) as xHappenings,
    SUM(IF(`destinationObjectType`='1',1,0) as yHappenings
  FROM `happenings`
  WHERE `userId` = ?

这肯定会在3列中返回您的结果。您的原始查询返回3行,但我认为这不是问题。

答案 1 :(得分:1)

SELECT 
    COUNT(*) AS totalHappenings,
    SUM(CASE WHEN `destinationObjectType` = \'2\' THEN 1 ELSE 0 END) AS xHappenings, 
    SUM(CASE WHEN `destinationObjectType` = \'1\' THEN 1 ELSE 0 END) AS yHappenings 
FROM `happendings` 
WHERE `userId` = ?

结果:

totalHappenings xHappenings yHappenings
      24            10          14

答案 2 :(得分:0)

尝试最短的方式:

SELECT COUNT(*) as totalHappenings, SUM(`destinationObjectType` = \'2\') AS xHappenings, SUM(`destinationObjectType` = \'1\') AS yHappenings FROM `happenings` WHERE `userId` = ? 

SUM内的比较返回true或false(1或0),因此不需要IFCASE语句