使用逗号分隔字段中的值选择行

时间:2016-12-28 06:57:50

标签: mysql

我必须从表'卖家'中选择一行,其中有两列'cat'和'place',其中多个ID以逗号存储

'seller' table
╔═══╦════════╦══════════════╗
║ id║cat     ║    place     ║
╠═══╬════════╬══════════════╣ 
║ 8 ║1,2     ║ 1,2,3,4      ║
╚═══╩════════╩══════════════╝

我的mysql查询

SELECT * FROM `seller` WHERE cat like '%1%' && place LIKE '%2%'

但我知道这是不好的查询。如果有12,它将被视为1和2。 有什么好的查询??。

1 个答案:

答案 0 :(得分:2)

使用FIND_IN_SET

SELECT * FROM `seller` 
WHERE find_in_set(1, cat) > 0
and find_in_set(2, place) > 0

但你应该改变你的桌面设计。

永远不要在一列中存储多个值!

这是一个经典的 n到m关系。更好的设计是

seller table
------------
id
name
...


categories table
----------------
id
name


seller_categories table
-----------------------
seller_id
category_id