mysql in 匹配规则,mysql强制结果的顺序与IN子句的顺序匹配

本文探讨如何修改SQL查询,使得包含IN子句的结果根据IN中的值顺序返回,例如progress=2在progress=4和7之前。原始查询中,结果按datetime排序,现需求针对特定session_id进行调整。通过使用GROUP_CONCAT和自连接解决,提高查询效率并保持指定的排列规则。
摘要由CSDN通过智能技术生成

This question is different to a commonly asked question about ordering the final results by the IN clause.

I would like to force the results returned by the query that contains the IN clause, to match the order of the IN clause.

I'd like to alter the query below so that a row containing progress=2 occurs before progress=4 and progress=7 for each session_id when ordering the formation_page_hits table by datetime.

Here is the current query:

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

These entries

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)

should be a match for the query, but:

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)

should not be a match.

Additionally:

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)

should be a match.

解决方案

The more common way is to double self-join to end up with a three way join ON ascending date time. That, however, is hardly a well performing query.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值