1

我有以下 2 个查询。

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'

是否可以将它们组合成一个查询?

第二个查询针对第一个查询的每个结果运行。

谢谢你。

见附上一小段 mysql 记录的图片。 在此处输入图像描述

我需要一个 mysql 查询来仅输出具有 action="MyAction" 作为给定 thread_id 集的最新记录的记录。在样本数据集中:用 Sr 记录:7201

我希望这有助于帮助我:)

4

4 回答 4

0

您可以使用 SELF JOIN,但不建议这样做,并且会影响您的查询性能。请检查以下查询以供参考

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'
于 2013-04-01T09:53:04.723 回答
0
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 
于 2013-04-01T09:56:31.910 回答
0
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

更新 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'
于 2013-04-01T10:03:57.970 回答
0

试试这个。

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'
于 2013-04-01T10:31:14.893 回答