[英]inner join with two tables in database
I have 2 tables in sql, and i am doing a query: 我在sql中有2个表,并且正在执行查询:
in the first query i am counting the data from a date 在第一个查询中,我从一个日期开始计算数据
In the secont query i am counting the data from a the same date 在第二次查询中,我正在计算同一日期的数据
And in the 3 query i am doing a inner join, but i need show the data that i have in the query 在3查询中,我正在做一个内部联接,但是我需要显示查询中的数据
20101120 26 19
But i have: 但我有:
20101120 313 313
I have the example in: 我有以下示例:
http://sqlfiddle.com/#!4/e61fc/2 http://sqlfiddle.com/#!4/e61fc/2
Who can help me? 谁能帮我?
What is the problem? 问题是什么?
I can do it with a join? 我可以加入吗?
Or the problem is the join? 还是问题在于加入?
SELECT A.id_date_sus AS id_date,
A.N1,
B.N2
FROM (SELECT id_date_sus,
COUNT(id_date_sus) AS N1
FROM suscription
GROUP BY id_date_sus) A
LEFT JOIN (SELECT id_date,
COUNT(id_date) AS N2
FROM billing
GROUP BY id_date) B
ON A.id_date_sus = B.id_date;
If you use oracle db, You can do something like: 如果使用oracle db,则可以执行以下操作:
with s1 as
(select id_date_sus, count(id_date_sus) c1
from suscription
group by id_date_sus),
s2 as
(select id_date, count(id_date) c2
from billing
group by id_date)
select s1.id_date_sus, s1.c1, s2.c2 from s1, s2 where s1.id_date_sus = s2.id_date
The problem is your data. 问题是您的数据。 There are only two services in each table.
每个表中只有两个服务。
So 所以
(s.id_service = b.id_service and
b.id_date = s.id_date_sus)
is not joining on a unique key. 没有加入唯一键。
When that happens we get a cartesian product, in which every record on one side of the join is paired to every record on the other side of the join. 发生这种情况时,我们得到一个笛卡尔乘积,其中联接一侧的每个记录都与联接另一侧的每个记录配对。 For
service_id=1
that produces (19*15) rows; 对于
service_id=1
产生(19 * 15)行; for service_id=2
that produces (4*7) rows. 对于产生(4 * 7)行的
service_id=2
。 Now, 285+28=313, which explains the count which troubles you. 现在,285 + 28 = 313,它说明了困扰您的计数。
The solution is to run the two counts as separate sub-queries and then join them in the main query: 解决方案是将两个计数作为单独的子查询运行,然后将它们加入主查询中:
select s.id_date_sus, s.cnt as s_cnt, b.cnt as b_cnt
from
( select s.id_date_sus, count(*) cnt
from suscription s
group by s.id_date_sus) s
join ( select b.id_date, count(*) cnt
from billing b
group by b.id_date) b
on (s.id_date_sus = b.id_date);
Here is my re-work of your SQL Fiddle . 这是我对您的SQL Fiddle的修改 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.