Logical AND operator in mySql REGEXP?

前端 未结 5 1617
名媛妹妹
名媛妹妹 2020-12-17 19:28

I use MySql REGEXP:

SELECT * FROM myTable
WHERE title REGEXP \"dog|cat|mouse\";

The dataset is small, so I am not concerned about performan

相关标签:
5条回答
  • 2020-12-17 19:32

    You can add several conditions with AND between them:

    SELECT * FROM myTable
    WHERE title REGEXP "dog" AND title REGEXP "cat" AND title REGEXP "mouse";
    

    Maybe REGEXP is not necessary here and you may use INSTR instead (regular are usually slower):

    SELECT * FROM myTable
    WHERE INSTR(title, "dog") AND INSTR(title, "cat") AND INSTR(title, "mouse");
    
    0 讨论(0)
  • 2020-12-17 19:39

    There's really no nice solution except concatenating ANDs:

    SELECT * FROM myTable
    WHERE title REGEXP "dog"
    AND title REGEXP "cat"
    AND title REGEXP "mouse"
    

    The regular expression would otherwise look like this:

    SELECT * FROM myTable
    WHERE title REGEXP "(dog.*cat.*mouse)|(dog.*mouse.*cat)|(mouse.*dog.*cat)|(mouse.*cat.*dog)|(cat.*dog.*mouse)|(cat.*mouse.*dog)"
    
    0 讨论(0)
  • 2020-12-17 19:51

    You can use full text search in boolean mode:

    SELECT * FROM table WHERE MATCH(colmun_name) AGAINST('+dogs +cat' IN BOOLEAN MODE);
    

    You must index your table first:

    ALTER TABLE table ADD FULLTEXT(column_name);
    
    0 讨论(0)
  • 2020-12-17 19:52

    If your title contains all the search terms, for example:

    Anything mouse anything cat anything dog anything

    Then you will have all the search terms in a three times repeated title in any order (for example dog, cat and mouse).

    Anything mouse anything cat anything DOG anything

    Anything mouse anything CAT anything dog anything

    Anything MOUSE anything cat anything dog anything

    So you can do this without concatenating ANDs with:

    SELECT * FROM myTable WHERE REPEAT(title,3) RLIKE '.*dog.*cat.*mouse.*';

    0 讨论(0)
  • 2020-12-17 19:55

    AND operation may be only accessible by the mysql-AND:

    WHERE title REGEXP 'dog' AND title REGEXP 'cat' AND title REGEXP 'mouse'
    

    this will only show those entries where all the keywords are in the title field. like

    title = "this is about mouse, cat and dog"
    
    0 讨论(0)
提交回复
热议问题