SQL Like and like

2020-02-15 02:53发布

问题:

Is it possible to string together multiple SQL LIKE wildcards in one query - something like this?

LIKE '% aaaa %' AND LIKE '% bbbb %'

The aim is to find records that contain both wild cards but in no specific order.

回答1:

The correct SQL syntax is:

field LIKE '% aaaa %' AND field LIKE '% bbbb %'


回答2:

Yes, that will work, but the syntax is:

Field LIKE '%aaa%' AND field LIKE '%bbb%'


回答3:

This is useful when you are using this statement with variables.

SELECT * 
FROM `tableName`
WHERE `colName` LIKE CONCAT('%', 'aaaa', '%') AND -- if aaaa is direct Text
      `colName` LIKE CONCAT('%', 'bbbb', '%')

SELECT * 
FROM `tableName`
WHERE `colName` LIKE CONCAT('%', aaaa, '%') AND -- if aaaa is variable
      `colName` LIKE CONCAT('%', bbbb, '%')


回答4:

Yes, but remember that LIKE is an operator similar to == or > in other languages. You still have to specify the other side of the equation:

SELECT * FROM myTable
WHERE myField LIKE '%aaaa%' AND myField LIKE '%bbbb%'


回答5:

It is possible to string together an arbitrary number of conditions. However, it's prudent to use parenthesis to group the clauses to remove any ambiguity:

SELECT *
  FROM tableName
 WHERE (columnOne LIKE '%pattern%')
   AND (columnTwo LIKE '%other%')


标签: php sql sql-like