2011-03-29 87 views
0

此問題與commonly asked question有關,通過IN子句排序最終結果。mysql強制結果的順序與IN子句的順序匹配

我想強制查詢返回包含IN子句的結果,以匹配IN子句的順序。

This is the original question我工作。

我想改變下面的查詢,以使得包含progress=2行由datetime訂購formation_page_hits表時progress=4progress=7每個session_id之前發生。

下面是當前查詢:

SELECT COUNT(*) 
FROM (
    SELECT session_id 
    FROM formation_page_hits 
    WHERE progress IN (2, 4, 7) 
      AND datetime >= '2011-03-23' 
      AND datetime < '2011-03-24' 
    GROUP BY 
      session_id 
    HAVING COUNT(DISTINCT progress) = 3 
    ) q 

這些條目

datetime,    session_id, progress 
('2011-03-01 01:02:11', 'abc',  2) 
('2011-03-01 01:02:12', 'abc',  4) 
('2011-03-01 01:02:13', 'abc',  7) 

應該是用於查詢的比賽,但是:

datetime,    session_id, progress 
('2011-03-01 01:02:11', 'abc',  4) 
('2011-03-01 01:02:12', 'abc',  2) 
('2011-03-01 01:02:13', 'abc',  7) 

不應該是一個匹配。

此外:

datetime,    session_id, progress 
('2011-03-01 01:02:11', 'abc',  4) 
('2011-03-01 01:02:12', 'abc',  2) 
('2011-03-01 01:02:13', 'abc',  4) 
('2011-03-01 01:02:14', 'abc',  7) 

應該是匹配的。

+0

(2,4,7)嚴格按升序排列。您的示例數據是否特殊,或者您希望始終使用升序? – vbence 2011-03-29 11:39:14

回答

1

更常見的方法是將自連接加倍,最終以三向加入ON升序日期時間結束。但是,這並不是一個表現良好的查詢。

select * 
from 
(
    SELECT session_id, group_concat(concat('|',progress,'/') order by datetime) list 
    FROM formation_page_hits 
    WHERE progress IN (2, 4, 7) 
      AND datetime >= '2011-03-23' 
      AND datetime < '2011-03-24' 
    GROUP BY session_id 
    HAVING COUNT(DISTINCT progress) = 3 
) X 
where list like '%|2/%|4/%|7/%'