简体   繁体   中英

Fetch records using JOIN with latest record using group by

counsellorlead table - 咨询台

feedback table- 反馈表

followup table- 随访表

Table 1 is counsellorlead

Table 2 - feedback

Table 3 -followup

Scenario is that on counsellor home page, data is display from all 3 table in below format -

Leadid | Mobileno | caller name | leadstatus | number of follow-ups | followupdate | next date

For this I am using 3 MySQL quires.

Now my query is that –

I am fetching records (leadid, mobileno, callername, leadstatus) from table 1(counsellor lead) and table 2(feedback) in first query using LEFT JOIN because I want all record from table 1(counsellor lead)

And in second query I am fetching record (no of followups) from table 3 (followup)

And from 3rd query I am fetching followup date and next date from table 3(followup)

Column description –

Number of followup - number of followups taken by particular leadid display here. (If 3 followup taken then result is 3)

Followup date - latest followup taken date display here. (If 3 followup taken then 3rd followup record)

Nextdate – date when next followup will be taken display here. (If 3 followup taken then 3rd followup record)

After fetch records from query 2 and query 3, I compare followup_lead_id column of followup table with leadid column of counsellorlead table using if else condition and when leadid match I display that record.

All records are display as per requirement, but it takes to much time, because of leadid comparison (there are around 12000 records in followups table and that will increase day by day). And this will increase page load time, normally it takes 15 min that is too much.

For the solution I have to fetch all 3 tables' data in a single query. But I am unable to create this single query to fetch records as per requirement.

Leadid | Mobileno | caller name | leadstatus | number of follow-ups | followupdate | next date

10125 | 95852***** | John | Fresh Lead | 3 | 16-06-2017 | 22-06-2017

 16-06-2017 is latest followup taken date of that particular lead

 22-06-2017 is a date when next followup will take                                              

Please help me out.

Try below query. I think it should work as you required.

select leadid, mobileno, callername, leadstatus,
( select count(fu.mobino) from followup fu
    where fu.followup_lead_id = cl.leadid ) num_follow_ups,
( select date_format(max(fu.followupdate), '%d-%m-%Y') from followup fu
    where fu.followup_lead_id = cl.leadid ) followupdate,
( select date_format(max(fu.nextdate), '%d-%m-%Y') from followup fu
    where fu.followup_lead_id = cl.leadid ) nextdate    
from counsellorlead cl
left join feedback fb on cl.leadid = fb.feedback_leadid
where cl.counsellorid = '1';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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