繁体   English   中英

如何计算 MySQL 中两个表之间不匹配的行数?

[英]How to count rows that aren't match between two tables in MySQL?

我有下表:

Users

ID    LastPaymentDate
1     2017-01-01
2     2018-02-05
3     2018-04-06
5     NULL

ActivityLog

ID    ActivityDate
1     2017-01-01
1     2017-05-17
3     2018-05-20

我需要找出具有LastPaymentDate但没有匹配ActivityDate的用户数量

上述数据的 output 结果为: 2UserID 3 和 2)。

我怎样才能做到这一点?

我们可以在这里尝试使用左联接方法:

SELECT u.ID, u.LastPaymentDate
FROM Users u
LEFT JOIN ActivityLog a
    ON u.ID = a.ID AND u.LastPaymentDate = a.ActivityDate
WHERE
    a.ID IS NULL AND u.LastPaymentDate IS NOT NULL;

在此处输入图片说明

演示版

使用NOT EXISTS

SELECT COUNT(*) 
FROM Users u
WHERE 
    u.LastPaymentDate IS NOT NULL
    AND NOT EXISTS (
        SELECT 1
        FROM ActivityLog a
        WHERE u.ID  = a.ID  AND u.ActivityDate = a.ActivityDate
    )

这种方法的好处是,即使在ActivityLog有多个匹配的记录,它也不会在Users的相同记录数倍。

我遇到了与此类似的问题。 我的决心是创建视图来显示字段和计数列。 然后我在视图之间进行了连接以显示 .net 结果:

CREATE ALGORITHM=UNDEFINED DEFINER=MySQL CURRENT_USER() SQL SECURITY DEFINER VIEW `subcr_count_x`  AS SELECT `x_subscriptions`.`user_id` AS `user_id`, count(0) AS `cnt` FROM `x_subscriptions` WHERE (`x_subscriptions`.`user_id` > 0) GROUP BY `x_subscriptions`.`user_id` ;

CREATE ALGORITHM=UNDEFINED DEFINER=MySQL CURRENT_USER() SQL SECURITY DEFINER VIEW `subcr_count_y`  AS SELECT `y_subscriptions`.`user_id` AS `user_id`, count(0) AS `cnt` FROM `y_subscriptions` WHERE (`y_subscriptions`.`user_id` > 0) GROUP BY `y_subscriptions`.`user_id`;

对于 select 没有匹配的记录,它会这样做。

SELECT * FROM 
`subcr_count_x` x INNER JOIN 
`subcr_count_y` y ON x.user_id = y.user_id 
WHERE x.cnt != y.cnt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM