MySql - Select 记录如字符串中存在的特定数字并以逗号分隔
MySql - Select records like a particular number present in a string and separated by commas
我有一个名为 product_info
的 table,其中包含以下数据:
+-------------+------------+----------------+
| title | slug | tags_id |
+-------------+------------+----------------+
| Maserti | /maserati | 10,34,7,110 |
| Ferrari | /ferrari | 10,34,7,107 |
| Rolls Royce | /rollroyce | 6,10,121,64,78 |
| Caterpillar | /cat | 4,8,210,214 |
| Peterbilt | /peterbilt | 8,100,210,214 |
+-------------+------------+----------------+
接下来我有一串 php:
$tag = ['id' => 10, 'slug' => 'luxurycars', 'title' => 'LuxuryCars'];
我想搜索我的 table 并查看我是否有任何带有此标签的记录。您可以看到标签的 ID 出现在 tags_id
行中。
如您所见,the id of the tag is '10'
。我尝试了很多查询,但结果总是不是我想要的。
例如:我想在 tags_id
中搜索 '10'
并且我希望它只匹配 '10'
但它匹配 10, 107, 110 and 210
和任何类似于或具有 [=21= 的数字] 在里面。
我期望的是当我搜索 '10'
(这是一个名为 LuxuryCars 的标签)时,我希望结果为 Maserati, Ferrari and Rolls Royce
(显然是被 tags_id 搜索,因为他们有在 table)
我不想在我的结果中出现 Peterbilt and Caterpillar
只是因为它们有一个关联的标签 210
。
请帮忙!
感谢您的宝贵时间!
要在逗号分隔的列表中搜索单个值,您可以使用 FIND_IN_SET()
:
SELECT *
FROM mytable
WHERE FIND_IN_SET('10', tags_id);
来自文档:
FIND_IN_SET(str,strlist)
Returns a value in the range of 1
to N
if the string str
is in the string list strlist
consisting of N
substrings. A string list is a string composed of substrings separated by ,
characters.
我有一个名为 product_info
的 table,其中包含以下数据:
+-------------+------------+----------------+
| title | slug | tags_id |
+-------------+------------+----------------+
| Maserti | /maserati | 10,34,7,110 |
| Ferrari | /ferrari | 10,34,7,107 |
| Rolls Royce | /rollroyce | 6,10,121,64,78 |
| Caterpillar | /cat | 4,8,210,214 |
| Peterbilt | /peterbilt | 8,100,210,214 |
+-------------+------------+----------------+
接下来我有一串 php:
$tag = ['id' => 10, 'slug' => 'luxurycars', 'title' => 'LuxuryCars'];
我想搜索我的 table 并查看我是否有任何带有此标签的记录。您可以看到标签的 ID 出现在 tags_id
行中。
如您所见,the id of the tag is '10'
。我尝试了很多查询,但结果总是不是我想要的。
例如:我想在 tags_id
中搜索 '10'
并且我希望它只匹配 '10'
但它匹配 10, 107, 110 and 210
和任何类似于或具有 [=21= 的数字] 在里面。
我期望的是当我搜索 '10'
(这是一个名为 LuxuryCars 的标签)时,我希望结果为 Maserati, Ferrari and Rolls Royce
(显然是被 tags_id 搜索,因为他们有在 table)
我不想在我的结果中出现 Peterbilt and Caterpillar
只是因为它们有一个关联的标签 210
。
请帮忙! 感谢您的宝贵时间!
要在逗号分隔的列表中搜索单个值,您可以使用 FIND_IN_SET()
:
SELECT *
FROM mytable
WHERE FIND_IN_SET('10', tags_id);
来自文档:
FIND_IN_SET(str,strlist)
Returns a value in the range of
1
toN
if the stringstr
is in the string liststrlist
consisting ofN
substrings. A string list is a string composed of substrings separated by,
characters.