1

我正在尝试在表中查找遵循特定模式的行。例如,有一个表有三列,分别是 ID、PRODUCT_ID 和 ACTION。

ID PRODUCT_ID 操作

1 A001 ABC
2 A001 DHI
3 A001 FGH
4 B111 FGH
5 A001 JKL
6 A001 ZAB

我想按顺序检索具有 3 个操作的记录,相同 PRODUCT_ID 的 ABC-FGH-ZAB。在上面的示例中,我想获取 ID 为 1、3 和 6 的行作为答案,ID 为 4 的行应该被忽略,因为它具有不同的 PRODUCT_ID。如何制定查询以在 MySQL 上获得如下结果集?

ID PRODUCT_ID 操作

1 A001 ABC
3 A001 FGH
6 A001 ZAB

我尽量不使用嵌套查询,除非出于性能原因必须这样做。ACTION 的顺序很重要,因此不应检索 FGH-ZAB-ABC。

提前致谢

4

2 回答 2

1
SELECT
    yt1.ID AS First,
    yt2.ID AS Second,
    yt3.ID AS Third
FROM
    YourTable yt1 
    JOIN YourTable yt2 
        ON yt2.ID > yt1.ID 
        AND yt2.Action = 'FGH' 
        AND yt2.Product_ID = y1.Product_ID
    JOIN YourTable yt3 
        ON yt3.ID > yt2.ID 
        AND yt3.Action = 'ZAB'
        AND yt3.Product_ID = y1.Product_ID
WHERE
    yt1.Action = 'ABC'
于 2012-03-06T22:14:21.537 回答
0

This will do the trick:

 select a.id from myActions a, (select ASCII(act) n, id from myActions) c 
 where char(c.n+1)=substring(a.act,2,1) and char(c.n+2)=substring(a.act,3,1)
 and a.id=c.id;

The table in example is:

 create table myActions( 
   id int(11) not null auto_increment,
   act char(3),
   primary key(id))


   insert into myActions (act) values
   ('ABC'),('DHI'),('EFG'),('LMN'),('XYV'),('XYZ'),('CBA'),('HIJ')

another option is a procedure.

table looks like this:

1   ABC
2   DHI
3   EFG
4   LMN
5   XYV
6   XYZ
7   CBA
8   HIJ

and result is: 1,3,4,6,8

UPDATE: at the end of the query add : and productId='A001' to get:

select a.id from myActions a, (select ASCII(act) n, id from myActions) c 
where char(c.n+1)=substring(a.act,2,1) and char(c.n+2)=substring(a.act,3,1)
and a.id=c.id and productId='A001';

You will need to specify the productId you seek as there may be two different productIds with matching sets.

于 2012-03-06T23:00:24.027 回答