简体   繁体   中英

How can I design the query to properly select from the database

The way I try to select: SELECT * FROM products_translate WHERE (category IN(10)) AND .....

The contents of the field in the database: category - 7, 10

This structured query only shows products that are only categorized by category 10 but not those that contain another category. For example 7, 10

How can I properly structure the query?

Database structure:

TABLE `products_translate` (
  `id` int(11) NOT NULL,
  `uniqueID` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `category` varchar(255) NOT NULL
)

Accordingly, the category field may contain: (1, 3, 7, 10)

One of the records in the database (109, 109, 'title', '7, 10')

My purpose is to select 7, 10 database requests to output all the entries they contain in the category 7 or 10 field.

如果您的数据库是 mysql,您可以使用FIND_IN_SET()

 SELECT * FROM products_translate WHERE FIND_IN_SET('7, 10',category)> 0

要查询等于 7 或 10 的类别,您只需在查询中添加 7。

SELECT * FROM products_translate WHERE category IN (10, 7)

If you do SELECT * FROM products_translate WHERE (category IN(10)) AND ..... you will only return row with category = 10 .

So you can do :

  • SELECT * FROM products_translate WHERE (category < 10) AND ... : if you want category 1, 2, 3 ... 10
  • SELECT * FROM products_translate WHERE (category IN(7, 10)) AND ... : if you want category 7 and 10 only
  • SELECT * FROM products_translate WHERE ... GROUP BY category : to return all element (according to you WHERE condition) but group by category (one element of each)
  • SELECT * FROM products_translate WHERE ... ORDER BY category : this way you will have your return elements order by category

Is it what you are looking for ?

EDIT : after you added some information about your table structure

SELECT * FROM products_translate WHERE (category LIKE '%10%') AND ... : this will select row where "10" is present in category field. But becareful, it will works with category like 105 or 810 too

Your category field is a bad idea : using a VARCHAR to put multiple category in one field is not very efficient...it should be an INTEGER and so for element with category 7 and 10 you should have 2 element in your table and not one. For this add UNIQUE INDEX on uniqueID + categoryID to avoid duplicate.

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