gpt4 book ai didi

mysql - 如何在 coumn_name 具有逗号分隔值的情况下运行 sql 查询?

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:57 24 4
gpt4 key购买 nike

CustomerID  cat_id  ContactName  Address    City    PostalCode  Country
1 Alfreds 13 Maria Anders Obere Str Berlin 12209 Germany
4 Around 13,14 Thomas Hardy 120 Hanov London WA1 1DP UK

获取 14 条数据的查询是什么?我试过了

SELECT * 
FROM `customers`
WHERE cat_id IN (13,14)

但失败了。

最佳答案

修正你的数据模型!为什么错了?

  • 数值应存储在具有正确类型的列中,而不是字符串。
  • 这些看起来像 ID。应正确定义外键关系。
  • SQL 的字符串处理能力很差。
  • 通常无法优化使用字符串操作的查询,从而优化使用索引、表统计信息和分区。
  • SQL 具有用于存储列表的非常好的数据结构。它被称为

因此,您应该有一个表,每个 customer_idcat_id 各占一行。这通常称为“连接表”或“关联表”。

也就是说,有时我们会受制于其他人非常、非常、非常糟糕的设计决策。如果是这样,您可以使用 find_in_set() 做您想做的事:

where find_in_set(13, cat_ids) > 0 and  -- or is that "or"
find_in_set(14, cat_ids) > 0

关于mysql - 如何在 coumn_name 具有逗号分隔值的情况下运行 sql 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50836172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com