gpt4 book ai didi

mysql - 如果一列有多个逗号分隔值,我如何过滤 mysql 数据?

转载 作者:行者123 更新时间:2023-11-29 01:29:05 25 4
gpt4 key购买 nike

我想问一下,如果对具有多个逗号分隔值的列进行条件检查,我该如何过滤 mysql 数据。我给你举个例子-

我有下表说“tbitems”-

id     item_names     item_types    item_features
1 item 1 8,6 10,5,4,9,8,6
2 item 2 8,6 10,5,8

现在假设我想获取项目类型为 8 或 6 但 item_features 完全等于我们指定的记录(项目),例如 10、5 和 4。

我知道第一个条件(项目类型)我们可以使用 IN 运算符。

但我不知道如何根据 item_features 过滤记录。

我可以这样写查询-

SELECT * FROMtbitemsWHEREitem_typesIN (8) ANDitem_features` 什么运算符(operator)应该在这里选择这些值 ( 4, 5, 10)

如果我像第一个条件一样使用 IN,那么上表的第二行也会被提取,因为集合 (10,5,8) 中有 5 和 10,但我只想提取第一行。有什么想法吗?

编辑 -

抱歉,您的解决方法无效。

我只想得到这张表的第一行 -

enter image description here

但现在它产生了一些我不想要的额外行。而且我不能使用这么多的 FIND_IN_SET 因为逗号分隔的值可能很大。我也不能在我的 PHP 代码中使用这个 sql。

最佳答案

对于您当前的场景,您可以在每次需要匹配item_features

时使用 FIND_IN_SET
SELECT * FROM
table1
WHERE
item_types
IN (8) AND FIND_IN_SET(4,item_features)
AND FIND_IN_SET(5,item_features)
AND FIND_IN_SET(10,item_features)

Fiddle Demo

But i ask youif its possible to change the schema then first normalize your structure see Database normalization,store all the relations in a separate table ,like a junction table for item_types_relations which store the current table id and all the items id in a junction table as one-to-many and a same junction table for item_features_relation

编辑 根据@Ravinder 的评论

SELECT * FROM
table1
WHERE
FIND_IN_SET(8,item_types)
AND FIND_IN_SET(4,item_features)
AND FIND_IN_SET(5,item_features)
AND FIND_IN_SET(10,item_features)

关于mysql - 如果一列有多个逗号分隔值,我如何过滤 mysql 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23006392/

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