如何在sql中存储然后通过CSV进行搜索?
我知道我可以使用 IN(1,2,3) 从 SQL 数据库中选择值为 1、2 或 3 的项目,但是如果我在 MYSQL 中有一个值,它是一个字符串,并且等于'1,2,3',我想选择该值。据我所知,我必须这样做:
SELECT whatever FROM wherever WHERE sqlvariable = '1' OR sqlvariable LIKE '1,%' OR `sqlvariable` LIKE '%,1,%' OR `sqlvariable` LIKE '%,1'
如果我想反向模拟“IN”,这很好。但是假设我想选择包含 1 或 2 的 sqlvariable,那么我必须这样做:
SELECT whatever FROM wherever WHERE sqlvariable = '1' OR sqlvariable LIKE '1,%' OR `sqlvariable` LIKE '%,1,%' OR `sqlvariable` LIKE '%,1' OR sqlvariable = '2' OR sqlvariable LIKE '2,%' OR `sqlvariable` LIKE '%,2,%' OR `sqlvariable` LIKE '%,2'
现在假设我使用 PHP 生成上述查询,并且我正在寻找包含 1 2 4 66 的 sqlvariable 34 33 22 44 或 992。运行此查询将花费相当长的时间。
我可以按位实现,但是我仅限于只有大约 60 个不同的项目,这还不够。
有没有更快的方法在 sql 中使用像上面这样的 CSV 查询?我想它有点像 IN() 但相反。
I know that I can use IN(1,2,3) to select items from an SQL database where their value is either 1, 2 or 3, but what if I have a value in MYSQL which is a string, and is equal to '1,2,3' and I want to select that value. As far as I know I have to do this:
SELECT whatever FROM wherever WHERE sqlvariable = '1' OR sqlvariable LIKE '1,%' OR `sqlvariable` LIKE '%,1,%' OR `sqlvariable` LIKE '%,1'
which is fine if I want to simulate 'IN' sort of in reverse. But lets say I want to select sqlvariable where it contains either 1 or 2, then I have to do this:
SELECT whatever FROM wherever WHERE sqlvariable = '1' OR sqlvariable LIKE '1,%' OR `sqlvariable` LIKE '%,1,%' OR `sqlvariable` LIKE '%,1' OR sqlvariable = '2' OR sqlvariable LIKE '2,%' OR `sqlvariable` LIKE '%,2,%' OR `sqlvariable` LIKE '%,2'
Now lets say I use PHP to generate the above queries and I'm looking to find sqlvariable where it contains a 1 2 4 66 34 33 22 44 or 992. It's going to take an awfully long time for this query to run.
I could do a bitwise implementation, but then I'm limited to only having about 60 different items or so which isn't enough.
Is there a faster way to utilize a CSV query like the above in sql? I suppose it's sort of like IN() but in reverse.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
简化查询FIND_IN_SET
:但这仍然需要搜索表中的每一行。最好重新设计数据库,以便不再需要 CSV 格式的数据。
更新:您现有的设计看起来像这样:
您应该将其更改为更像这样的东西:
You can simplify your queries using
FIND_IN_SET
:This however will still require searching every row in the table. It would be better to redesign your database so that CSV formatted data is not required.
Update: Your existing design looks something like this:
You should change it to something more like this: