Question

I have the following 2 queries.

Query 1 : 
select distinct(thread_id) from records where client_name='MyClient'

Query 2 :
select max(thread_no) from records 
where thread_id='loop_result_from_above_query' AND action='Reviewed'

Is it possible to combine them into a single query ?

The second query is run on every result of the first query.

Thank you.

See attached image of a small snippet of mysql records. enter image description here

I need a single mysql query to output only records which have action="MyAction" as the latest records for a given set of thread_ids. In the sample data set : record with Sr: 7201

I hope this helps in helping me :)

Was it helpful?

Solution

SELECT  client_name, thread_id, MAX(thread_no) max_thread
FROM    records
WHERE   action='Reviewed' AND client_name='MyClient'
GROUP   BY client_name, thread_id

UPDATE 1

SELECT  a.*
FROM    records a
        INNER JOIN
        (
            SELECT  thread_id, max(sr) max_sr
            FROM    records
            GROUP   BY thread_id
        ) b ON a.thread_id = b.thread_id AND
                a.sr = b.max_sr
WHERE   a.action = 'MyAction'

OTHER TIPS

You can use SELF JOIN, but it is not advisable and will impact your query performance. Please check below query for your reference

SELECT DISTINCT r1.thread_id, MAX(r2.thread_no) from records r1 LEFT JOIN records r2 ON r2.thread_id=r1.thread_id WHERE r1.client_name='MyClient' AND r2.action='Reviewed'
SELECT a.maxthreadid, 
       b.maxthreadno 
FROM   (SELECT DISTINCT( thread_id ) AS MaxThreadId 
        FROM   records 
        WHERE  client_name = 'MyClient') a 
       CROSS JOIN (SELECT Max(thread_no) AS MaxThreadNo 
                   FROM   records 
                   WHERE  thread_id = 'loop_result_from_above_query' 
                          AND action = 'Reviewed') b 

Try this.

SELECT * 
FROM   (SELECT Row_number() 
                 OVER ( 
                   partition BY thread_id 
                   ORDER BY thread_no)      no, 
               Max(thread_no) 
                 OVER( 
                   partition BY thread_id ) Maxthread_no, 
               thread_id, 
               action, 
               client_name 
        FROM   records
        Where client_name = 'MyClient') AS T1 
WHERE  no = 1 
       AND action = 'Reviewed'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top