mysql中的Count()函数

时间:2015-06-11 18:19:27

标签: mysql count

我的count函数计算第一个表的记录两次然后添加到相同的结果而不是添加两个表记录的count()。我该如何解决这个问题?

SELECT 
uln.user_id, count(uln.user_id)+count(uln.user_id) as user_pet_notif_count
FROM
user_legislation_notifications uln
join user_petition_notifications upn
on upn.user_id = uln.user_id
where
uln.user_id = '7' and uln.isRead = '0'
and upn.user_id = '7' and upn.isRead = '0'

结果是user_id - > 7 user_pet_notif_id - > 28而不是user_id - > 7 user_pet_notif_id - > 9

2 个答案:

答案 0 :(得分:0)

count(uln.user_id)+count(uln.user_id)中,您要添加两次uln.user_id。不应该是upn.user_id

答案 1 :(得分:0)

您需要在不加入的情况下进行计数,否则您需要计算加入结果中的行数。

SELECT (SELECT COUNT(*)
        FROM user_legislation_notifications
        WHERE user_id = '7' and isRead = '0')
    +  (SELECT COUNT(*)
        FROM user_petition_notifications
        WHERE user_id = '7' and isRead = '0') AS user_pet_notif_count