如何在两个不同的表格上添加两个计数(*)结果?

我有两个表:玩具和游戏。

+--------------------+------------------+ | Field | Type | +--------------------+------------------+ | toy_id | int(10) unsigned | | little_kid_id | int(10) unsigned | +--------------------+------------------+ +--------------------+------------------+ | Field | Type | +--------------------+------------------+ | game_id | int(10) unsigned | | little_kid1 | int(10) unsigned | | little_kid2 | int(10) unsigned | | little_kid3 | int(10) unsigned | +--------------------+------------------+ 

一个小孩可以有多个玩具。 一个小孩可以一次参加多个游戏。

我想要一个查询,它会给我一个little_kid参与的玩具+游戏总数。

基本上,我想这两个查询的总和:

 SELECT COUNT(*)FROM WHERE little_kid_id = 900;
 SELECT COUNT(*)from WHERE little_kid1 = 900 
                              或little_kid2 = 900 
                               OR little_kid3 = 900;

是否有可能在一个单一的SQL查询? 显然,我可以通过编程来对它们进行求和,但这不太理想。

(我意识到这个人为的例子使模式看起来无效,我们假设我们不能改变模式。)

把它们包起来并使用子查询:

 SELECT (SELECT COUNT(*) FROM Toys WHERE little_kid_id = 900)+ (SELECT COUNT(*) from Games WHERE little_kid1 = 900 OR little_kid2 = 900 OR little_kid3 = 900) AS SumCount 

瞧!

 SELECT COUNT(1) FROM ( SELECT 1 FROM Toys WHERE little_kid_id = 900 UNION SELECT 1 FROM Games WHERE little_kid1 = 900 OR little_kid2 = 900 OR little_kid3 = 900 ) 

根据这个查询可能运行的多less以及数据更改的频率,您可以定期将数据放入如下所示的聚合表中:

 CREATE TABLE aggregated ( little_kid_id INT UNSIGNED, games_count INT UNSIGNED, toys_count INT UNSIGNED, PRIMARY KEY (little_kid_id) ); 

性能明智,这将是快速和避免任何讨厌的子查询。

试试这个…

 db: mysql SELECT SUM(dum.tab) AS total FROM ( SELECT COUNT(b.category_id) AS tab FROM tblcategory AS b WHERE b.category_id=1 UNION ALL SELECT COUNT(a.category_id) AS tab FROM tblcategory AS a WHERE a.category_id=2 ) AS dum 
  SELECT M.*,M.TOYSCOUNT+M.GAMECOUNT FROM ( (SELECT COUNT(*) FROM Toys WHERE little_kid_id) AS TOYSCOUNT, (SELECT COUNT(*) from Games WHERE little_kid1 = 900 OR little_kid2 = 900 OR little_kid3 = 900) AS GAMECOUNT ) M