mysql强制命令结果发现匹配IN子句的顺序

时间:2011-03-29 10:57:03

标签: mysql sql-order-by having sql-in

这个问题与关于按IN子句排序最终结果的commonly asked question不同。

我想强制包含IN子句的查询返回的结果,以匹配IN子句的顺序。

我正在工作的

This is the original question

我想更改下面的查询,以便在订购progress=2时,progress=4之前包含progress=7的行和session_id formation_page_hitsdatetime

以下是当前查询:

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)

应该是匹配。

1 个答案:

答案 0 :(得分:1)

更常见的方法是将自我加入加倍,最后以升序日期时间进行三向连接。然而,这几乎不是一个表现良好的查询。

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/%'