0

我在尝试查询以下数据时遇到问题:

id. | name | type

 1.    bob | a 
 2.    sam | ab
 3.    jim | abc
 4.  sarah | ad
 5.   john | a
 6.    eve | bca
 7.  nikki | ca

我正在尝试根据以下输入编写 MySQL 查询:

a,
ac,
b*,
ac*

我想返回以下名称:

bob
john
sam
jim
eve
nikki

分解:

a  = bob, john
ac = nikki  
b* = sam, jim, eve
ac*= jim, eve, nikki

解释:

a  = find results that are JUST a
ac = find results that contain ONLY an a AND c
b* = find results which contains a b
ac*  find results that contain at least an a and a c

可以看出,类型列可以包含不同顺序的类型信息(并不总是增加)。

我确信这可以通过将类型列拆分为等来完成,然后type_a在每个列中添加一个。但这可能会上升,我不想在我的桌子上多放 26 列!type_bboolz

这是否可以在单个查询中完成,如果可以,任何帮助将不胜感激!

对不起标题我不知道该怎么称呼它

4

2 回答 2

1
-- ac*, ac, a, b*

SELECT  *
FROM    mytable
WHERE   (
        type RLIKE 'a'
        AND type RLIKE 'c'
        )
        OR
        (
        type RLIKE 'a'
        AND type RLIKE 'c'
        AND NOT type RLIKE '[^ac]'
        )
        OR
        (
        type RLIKE 'a'
        AND NOT type RLIKE '[^a]'
        )
        OR
        (
        type RLIKE 'b'
        );

不过,这不会使用任何索引。

如果您的表是MyISAM,您可以存储如下类型:

id   name     type
7    nikki    a c

(注意空格)并使用FULLTEXT功能:

CREATE FULLTEXT INDEX fx_mytable_type ON mytable (type);

-- ac*
SELECT  *
FROM    mytable
WHERE   MATCH(type) AGAINST '+"a" + "c"' IN BOOLEAN MODE);


-- ac
SELECT  *
FROM    mytable
WHERE   MATCH(type) AGAINST '+"a" + "c"' IN BOOLEAN MODE);
        AND NOT TYPE RLIKE '[^ ac]' -- note the space

设置@@ft_min_word_len = 1为此工作。

于 2012-04-27T12:02:39.710 回答
1

您可以使用正则表达式

SELECT name FROM your_table WHERE
     type RLIKE '^a+$'                            -- only 'a'
  OR type RLIKE '^((a[ac]*c)|(c[ac]*a))[ac]*$'    -- only & both 'a' AND 'c'
  OR type RLIKE 'b'                               -- at least one 'b'
  OR type RLIKE '(a.*c)|(c.*a)'                   -- at least 'a' and 'c'
;
于 2012-04-27T12:03:31.243 回答