我有一个MySQL表,我将在其中存储用户的email_id
以及用户的关注者email_id
。它的列是:
ID, USER_EMAIL, FOLLWING_EMAIL
现在,当用户登录到他的帐户时,我想计算:
计算他关注的人数很简单:
select count(*) from list where user_email = <logged-in email>
但是如何计算只有一个查询中有多少人关注他?
答案 0 :(得分:2)
我认为您只需要更改WHERE子句中的字段:
SELECT count(*) FROM list WHERE following_email = '...'
要在一个查询中计算两者,请使用子选择:
SELECT
(SELECT count(*) FROM list WHERE user_email = '...') AS following,
(SELECT count(*) FROM list WHERE following_email = '...') AS followers
是否有任何优化来存储数据,以实现此功能?
是。在USER_EMAIL
上添加索引,在FOLLOWING_EMAIL
上添加另一个索引。
答案 1 :(得分:1)
SELECT
COUNT(CASE WHEN user_email = '<email>' THEN 1 ELSE NULL END) AS following_cnt,
COUNT(CASE WHEN following_email = '<email>' THEN 1 ELSE NULL END) AS follower_cnt
FROM
list
WHERE
'<email>' IN (user_email, following_email)
答案 2 :(得分:0)
此用户关注的人的电子邮件地址是FOLLOWING_EMAIL吗?或者是另一个表的索引?如果是前者,那么:
SELECT COUNT(*) from list where FOLLOWING_EMAIL="test@test.com"