【问题标题】:select a row using a value in comma separated fields使用逗号分隔字段中的值选择一行
【发布时间】:2017-05-12 10:23:54
【问题描述】:

我必须从表 'seller' 中选择一行,该表有两列 '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。 有什么好的查询吗??

【问题讨论】:

标签: mysql


【解决方案1】:

使用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

【讨论】:

  • 谢谢。您的查询工作正常。我使用多选下拉菜单存储在两列中,这就是我使用逗号的原因。
  • 没有理由在列中使用逗号分隔的列表。没有!
猜你喜欢
  • 1970-01-01
  • 2012-03-20
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
相关资源
最近更新 更多