基于JOIN的列复制的MySQL SUM

时间:2018-09-04 22:44:22

标签: mysql sql

我有这两个表

subtitles_request

movie_id | user_id | sent
2002     |    1    |   1
2002     |    2    |   1
2002     |    3    |   1
2002     |    4    |   1
2002     |    5    |   1
2002     |    6    |   1
2002     |    7    |   1
2002     |    8    |   1

电子邮件计划

movie_id | schedule_id
2002     |  1
2002     |  2

这是我的查询

SELECT SUM(a.sent) as sent FROM subtitles_request a
JOIN email_schedule c on c.movie_id=a.movie_id

问题出在查询SUM(a.sent) as sent的这一部分。 sent被复制,因为它们是在email_schedule上被连接的两行。因此,我得到的不是8,而是16

我该如何解决,所以sent列不会加倍?

1 个答案:

答案 0 :(得分:2)

您可以尝试在DISTINCT movie_id的子查询中添加email_schedule,因为email_schedule表中有两行是movie_id = 2002,遗嘱与{{1 }}表,其中subtitles_request

因此您将获得movie_id = 2002数据行。

2*8 = 16

查询1

CREATE TABLE subtitles_request(
    movie_id INT,
    user_id INT,
  sent INT
);


INSERT INTO subtitles_request VALUES (2002,1 ,1);
INSERT INTO subtitles_request VALUES (2002,2 ,1);
INSERT INTO subtitles_request VALUES (2002,3 ,1);
INSERT INTO subtitles_request VALUES (2002,4 ,1);
INSERT INTO subtitles_request VALUES (2002,5 ,1);
INSERT INTO subtitles_request VALUES (2002,6 ,1);
INSERT INTO subtitles_request VALUES (2002,7 ,1);
INSERT INTO subtitles_request VALUES (2002,8 ,1);
CREATE TABLE email_schedule
(
    movie_id INT,
    schedule_id INT
);

INSERT INTO email_schedule VALUES (2002,  1);
INSERT INTO email_schedule VALUES (2002,  2);

Results

SELECT SUM(a.sent) as sent 
FROM subtitles_request a
JOIN (SELECT DISTINCT movie_id  FROM email_schedule) c on c.movie_id=a.movie_id