问题描述
现在有3个表 A、B、CA表字段有:user_id,timestamp ...B表字段有:user_id,timestamp ...C表字段有:user_id,timestamp ...A、B、C三个表的user_id字段有重复的值,现在我想要把A、B、C这三张表的所有user_id联合起来算出count(*),并且去除重复的值。请问sql语句要怎么写?
解决方案
select count(1) from (SELECT t1.user_id from t1union select t2.user_id from t2UNIONselect t3.user_id from t3) aunion本身就去除重复了,count(1)用于统计,使用常量能提高效率
解决方案二:
select count(user_id) from (select user_id from A union all select user_id from B union all select user_id from C) group by user_id顺带一提kjmmlzq19851226 的方法一定是错的,a表如果没有数据,b,c表都有数据,那它的方法是查不出数据的。
解决方案三:
需要分组。e.g.SELECT COUNT(1) FROM (SELECT 1 FROM A a, B b, C c WHERE a.user_id=b.user_id AND a.user_id=c.user_id AND b.user_id=c.user_id GROUP BY a.user_id);
解决方案四:
SELECT COUNT(*) from (SELECT user_Id from usera UNION SELECT user_Id from userb UNION SELECT user_Id from userc) as ttt;