Get the No of Pending, Accepted and Rejected Users from two tables

时间:2017-11-13 06:37:52

标签: mysql

I have two tables namely register and expressinterest

Where register table contains (user related columns) some are -

i) matri_id (unique but not primary)

ii) mobile

iii) email

iv) last_login

and expressinterest table contains data related to the matches details where columns are namely

i) ei_sender

ii) ei_receiver

iii) ei_response

iv) ei_sent_date

I am comparing the matri_id of register table to ei_sender and ei_receiver of expressinterest table, where one user can send requests to another users and he can receive request from another users.

I have to get the count of Pending, Accepted and Rejected status of all the users present in the register table, but when I am running the query it's running very slow, It takes around 45-60 seconds to fetch only 5000 rows in which the data is not proper (a single ID is coming in 3 rows like Accepted in one row, Rejected in one row and Pending in one row), But I want all the counts to come in a single row like this

r.matri_id | r._email | r.mobile | pending_count | accepted_ count | rejected_count| r.last_login

Some queries which I had tried so far are

select r.matri_id, r.email, r.mobile, r.last_login, e.receiver_response, count(e.receiver_response), e.ei_sender, e.ei_receiver from register r, expressinterest e where r.matri_id = e.ei_sender or r.matri_id = e.ei_receiver GROUP BY e.receiver_response, r.matri_id ORDER BY r.last_login DESC

This is what I want but its taking 5-6 seconds to execute

select matri_id, email, mobile, last_login, (select count(ei_sender) from expressinterest where ei_receiver=matri_id and receiver_response = 'Pending') AS pending_count_mine, 
(select count(ei_sender) from expressinterest where ei_sender=matri_id and receiver_response = 'Accepted') AS accepted_count,
(select count(ei_sender) from expressinterest where ei_sender=matri_id and receiver_response = 'Rejected') AS rejected_count FROM register ORDER BY last_login DESC 

Thanks

1 个答案:

答案 0 :(得分:0)

您可以使用单个子查询和左连接替换多个相关子查询:

select r.matri_id,
    r.email,
    r.mobile,
    r.last_login,
    t.accepted_count,
    t.rejected_count,
    t.pending_count
from register r
left join (
    select ei_sender, 
        sum(receiver_response = 'Accepted') as accepted_count,
        sum(receiver_response = 'Rejected') as rejected_count,
        sum(receiver_response = 'Pending') as pending_count
    from expressinterest
    where receiver_response in ('Rejected', 'Accepted', 'Pending')
    group by ei_sender
    ) t on r.matri_id = t.ei_sender;