mysql 查询id逗号隔开,MYSQL逗号分隔的ID与分隔的表

Consider a table products which has product details including its category. One product may belong to multiple category so I'm keeping it as a comma separated list of category IDs.

I know this is not normalized approach.

Can any MYSQL expert tell me that which approach will be faster for selecting products of a particular category.

Obviously we have to JOIN products table and products_category_relation table if take normalized approach.

AND

In my approach we have to write a like query to find the products (assume we are searching for category id 10)

SELECT p.*

FROM products p

WHERE p.category like '10'

OR p.category like '10,%'

OR p.category like '%,10'

OR p.category like '%,10,%'

Can any one tell me if this approach is faster or the JOIN approach will be faster?

I know about normalization. I know about other risks involved in my approach. But they do not matter in my case. So, I'm concerned with speed.

Any theoretical explanation about its speed or a practical test result are welcome.

UPDATE

I'm using myISAM engine

product table has Primary Key product_id

FullText index on category column of products table

解决方案

A database conforming to the first normal form will be much faster. Your example query cannot use any index and requires a full table scan to resolve. Worse, it must scan the entire text field for all the rows and text work is almost always more expensive than integer work for the computer.

A normalized table can easily use an index on the category column to speed up the query.

Text storage may also require more space on disk since numbers are usually more expensive when saved as characters than as the correct integer type (of course there's some overhead involved in row storage as well).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值