在一个mysql查询中计算两个不同事物的最简单方法

时间:2017-01-04 14:38:00

标签: mysql sql

我正在测试一种从单个mysql表中计算两种不同内容的方法。

检查是否已声明游戏密钥,以便我可以在页面中执行声明/总计数的计数器。

SELECT 
  (SELECT COUNT(`id`) FROM `game_giveaways_keys` WHERE `claimed` = 1 AND `game_id` = 3) as `claimed`,
  (SELECT COUNT(`id`) FROM `game_giveaways_keys` WHERE `game_id` = 3) as `total`
FROM game_giveaways_keys 
LIMIT 1

如果我没有添加" LIMIT 1"它向我显示与有多少行相同的声明/总数,我只是将它限制为1行,或者是否有更好的方法将我想要的信息仅限于1行开始?

2 个答案:

答案 0 :(得分:4)

使用条件聚合:

SELECT SUM(CASE WHEN claimed = 1 AND game_id = 3 THEN 1 ELSE 0 END) AS claimed,
       SUM(CASE WHEN game_id = 3 THEN 1 ELSE 0 END) AS total
FROM game_giveaways_keys

这也可以简化为:

SELECT SUM(CASE WHEN claimed = 1 THEN 1 ELSE 0 END) AS claimed,
       COUNT(*) AS total
FROM game_giveaways_keys
WHERE game_id = 3

这两个查询都比原始方法有优势,因为它们只需要一次扫描,而使用两个独立的子查询则需要至少两次全表扫描。

答案 1 :(得分:1)

FROM之后你不需要提供任何东西。您的完整查询应该只是:

SELECT 
  (SELECT COUNT(`id`) FROM `game_giveaways_keys` WHERE `claimed` = 1 AND `game_id` = 3) as `claimed`,
  (SELECT COUNT(`id`) FROM `game_giveaways_keys` WHERE `game_id` = 3) as `total`