简体   繁体   中英

Select items that may be related (like: for 'orange', give 'bread') from MySQL database using PHP

I have a system in which I have to select "similar" records. Imagine a database containing a big list of products and when the user enters partial name of a product, a list of products come up as suggestions about the product he is searching for. These products have a longer description field too.

This is NOT about a WHERE product_name LIKE '%entered_string%' query, I think. The logic is akin to the one Stack Overflow might use, id est: when you ask a question, it prompts you with Questions that may already have your answer and Similar questions , both obviously using a method to derive what I want to ask from my question title/content and search against the database, showing the results.

I just wonder whether it is accomplishable with PHP and using MySQL as the database.

Example: Entering food should give us results like 1kg oranges , bread and cookies . Both of these would have something similar which could help to link them programmatically to each other.

There can lots of methods to approach this scenario . but I think straight one is to have multiple keywords/tags mapped with every item. so when user types in, you would not be searching item table , you should be searching the mapped keywords and based on that searching loading the relevant items.

If you want similar products to show up, you need to put that information in your database. So, make a category for foods, and assign every food product to that category. That way you can select similar products easily. There is no other efficient way to do this

So your database:

categories:
|id|name
 1    fruit
 2    Cars

Products
|id|name|category_id
  1  apple 1
  2  Ford focus  2

And you can select like this:

SELECT `name`,`id` FROM `products` WHERE category_id = 1;

Another way (as suggested in a comment) are tags

Products
|id|name|tags
  1  apple "fruit food delicious" 
  2  Ford focus  "Car wheels bumper"

Best way is to use a fulltext search on the tags:

SELECT * FROM `products` WHERE MATCH(tags) AGAINST ('fruit')

Make sure to have a fulltext index on tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM