我在尝试查询以下数据时遇到问题:
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列可以包含不同顺序的类型信息(并不总是增加)。
我确信可以通过将类型列拆分为type_a
,type_b
等等来完成,然后在每个列中都有一个bool
。但这可能会达到z
而且我不想在我的桌子上加上26个额外的cols!
这可以在单个查询中执行,如果有的话,任何帮助都会受到赞赏!
对标题感到抱歉我不知道该怎么称呼它
答案 0 :(得分: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
以使其生效。
答案 1 :(得分:1)
您可以使用regular expressions:
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'
;