MYSQL - 计算具有相同列名的多个表的行总数

时间:2014-05-21 15:49:51

标签: mysql

我有三张桌子:a_survey,b_survey和c_survey。这些表中的每一个都有一个column_name" user_id"。我想要做的是计算实际发布的调查并将该值返回到一行。因此,如果找到一条记录,其中每个表都有匹配的user_id,则计数将返回3.

以下是我尝试的内容:

select count(user_id) AS total_of_surveys 
  FROM a.survey, b.survey, c.survey 
 WHERE user_id = 3;

但我收到错误:

Column 'user_id' in field list is ambiguous

提前致谢!

3 个答案:

答案 0 :(得分:2)

select sum(count(a.survey.user_id)+count(b.survey.user_id)+count(c.survey.user_id)) AS total_of_surveys 
  FROM a.survey, b.survey, c.survey 
 WHERE user_id = 3;

答案 1 :(得分:1)

您尝试过的是一个笛卡尔计划,它会将结果乘以每张桌子上的注册表数量。

做你想做的事的正确方法是加入(使用左连接)或'UNION'表格如:

select count(user_id) from
(select user_id from a_survey where user_id = 3 UNION ALL
select user_id from b_survey where user_id = 3  UNION ALL
select user_id from c_survey where user_id = 3) tables

答案 2 :(得分:0)

您需要单独计算每个表并将它们加在一起。如果需要,可以使用一个(丑陋的)查询执行此操作。这样的事情应该有效:

Select (select  count(user_id) FROM a.survey WHERE user_id = 3) + (select  count(user_id) FROM b.survey WHERE user_id = 3) + (select  count(user_id) FROM c.survey WHERE user_id = 3) as total_of_surveys;