MYSQL search fields method

空扰寡人 提交于 2019-12-14 02:16:14

问题


Please help, I'm very confused about my situation.

I'm beginning to create a search function but I'm not sure the best way to go about it. On the front-end users will be able to enter words in a text-field, then these will search the MYSQL database, something like below:

so they search for 'Adult' and every item_id (Primary Key) with 'Adult' in column 'name' is listed. Or they enter 'black' and every item_id with 'black' in 'colors' is listed. or they enter 'Adult Blue' and every item with either 'Adult' or Blue would come up. I'm sure you get the idea.

I've read up on multiple methods, but I can't figure out which is best:

Using a MANY TO ONE table: This seems like it would work, but there are over 500 unique items, so that would be thousands and thousands of rows. For item_id 1 I would have to make a row for 'Adult', a row for 'Denim', a row for 'Pants', a row for 'black', a row for 'red', a row for 'blue'. I might as well just hard code everything.

Using FIND_IN_SET: Is this going to work? Would I have to store the values with commas like Adult,Denim,Pants and also EXPLODE to separate the values? I was going to try this method but I keep reading that storing multiple values in a field is very bad practice.

Or are Regular Expressions what I'm looking for?

What is the best way to store the values, and what is the best way to retrieve them? I'm not asking for exact code, just the methods to use. Any advice is appreciated!


回答1:


So, if we suppose that columns name and colors are the only columns we need to search through, I'd do the following (naive solution but will work fine if your DB doesn't have millions of rows and you don't have thousands of customers searching at once).

First, create a view

CREATE VIEW SearchHere AS
SELECT item_id, CONCAT(name, ' ', colors) AS FullDescription
FROM table

I don't know the name of the table in your screenshot, so I used table as its name.

Now, if a user searches for adult red pants you could issue a query

SELECT item_id
FROM SearchHere
WHERE FullDescription LIKE '%adult%'
AND FullDescription LIKE '%red%'
AND FullDescription LIKE '%pants%'

Of course, you'd need to generate the query on the fly but that's not an issue. You could play with using AND or OR and placing spaces in between the wildcrad symbol % and the search term. Probably you would also want to do the view in a more sophisticated way, e.g., do more tha just CONCAT.




回答2:


A straightforward solution is to use

name REGEXP 'the|search|terms'
OR colors REGEXP 'the|search|terms'

You should explain what you mean by best, though -- fastest performance? easiest to maintain? other?



来源:https://stackoverflow.com/questions/19361676/mysql-search-fields-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!