문제

I'm trying to find a query that returns a list of matching words found in a text field in a mySQL database. The trick is that the text field contains multiple other words that I don't want returned.

Consider as an example a database of cars, where a "colours" text field contains all the colours on the car.

Say we have rows with these entries in the 'colours' field:

"candy apple red, black"
"reddish brown"
"sunset red, white"
"Purple, Cherry red, pink polkadots"
"white"
"sunset red"

I can do this:

SELECT colours from CARS WHERE colours REGEXP 'red'

which returns all the rows that have 'red' in it somewhere, but it returns everything in that field.

The trick is that I want the resulting list to look like this:

"candy apple red"
"reddish brown"
"sunset red"
"cherry red"

At the moment I'm considering using PHP to get the full results list from the server and then working through the list from there. But that can get costly if the database gets large.

Thanks!

Edit:

Here is a partial answer which only includes the first colour found in any of the 'colours' fields (and removes duplicates), and it's not too nasty a query:

SELECT distinct
TRIM(CONCAT(SUBSTRING_INDEX(SUBSTRING(colours, 1, LOCATE('red',colours)-1), ',' , -1),
SUBSTRING_INDEX(SUBSTRING(colours, LOCATE('red',colours)), ',' ,  1) ))as found
FROM CARS
WHERE colours REGEXP 'red'

Ideally we could extend this to also account for multiple occurrences in a field. For example, if we had a field like this: "Purple, Cherry red, pink polkadots, Sunset Red"

올바른 솔루션이 없습니다

다른 팁

Here is a way you can do this, but it is not particularly "nice":

SELECT (case when substring_index(colours, ', ', 1) like '%red%'
             then substring_index(colours, ', ', 1)
             when substring_index(colours, ', ', 2) like '%red%'
             then substring_index(substring_index(colours, 2), ', ', -1)
             when substring_index(colours, ', ', 3) like '%red%'
             then substring_index(substring_index(colours, 3), ', ', -1)
             when substring_index(colours, ', ', 4) like '%red%'
             then substring_index(substring_index(colours, 4), ', ', -1)
             . . .
        end)
from CARS
WHERE colours like '%red%';

You need to manually extend the query to the longest list in the data. And, this returns the first matching item, not all of them.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top