[英]How to extract one value from imploded array in MySQL row
I'm using implode to insert few values into one row in MySQL database.我正在使用 implode 在 MySQL 数据库的一行中插入几个值。
implode(' ', $_POST['tag']);
Assuming that I have table named product
with row named tags
with 3 different values that inserted inside like this:假设我有一个名为
product
表,其中的行命名为tags
其中包含 3 个不同的值,如下所示:
usb adapter charger
I have tried using this method using like operator ( %
), but that didn't worked.我曾尝试使用 like 运算符 (
%
) 使用此方法,但这没有用。
$sql = "SELECT * FROM product WHERE tags='%usb%'";
How can I extract only one value from the imploded array using WHERE in mysql query?如何在 mysql 查询中使用 WHERE 从内爆数组中仅提取一个值?
I agree with the comments about re-designing the database.我同意有关重新设计数据库的意见。 At first read it seems that using
LIKE
would definitely get the result you want but after reading @Patrick Q's pan - panther example, it makes a lot sense that LIKE
is not really a good solution.乍一看,似乎使用
LIKE
肯定会得到您想要的结果,但是在阅读了@Patrick Q 的 pan - panther 示例之后, LIKE
并不是一个很好的解决方案是很有意义的。 There are ways to get exactly the tag string you're looking for but it may hurt the performance and the query will be longer and complex.有多种方法可以准确获取您正在查找的标签字符串,但它可能会影响性能,并且查询会更长且更复杂。 Hence the following are to demonstrate how the query would look like with your current
tags
data value:因此,以下内容将演示使用当前
tags
数据值查询的样子:
MySQL query:
SELECT tags,
SUBSTRING_INDEX(SUBSTRING_INDEX(tags,' ',FIND_IN_SET('usb',REPLACE(tags,' ',','))),' ',-1) v
FROM mytable
HAVING v = 'usb';
As you can see, there are a few functions being used just to get the exact string from the data cell.如您所见,有一些函数用于从数据单元格中获取确切的字符串。 Since your example data was separating with spaces and
FIND_IN_SET
identify value separation by comma, REPLACE
take place on the tags
column first to replace spaces with comma.由于您的示例数据用空格分隔,而
FIND_IN_SET
用逗号标识值分隔,因此首先在tags
列上进行REPLACE
以用逗号替换空格。 Then with SUBSTRING_INDEX
twice to get the string using the location extracted in FIND_IN_SET
.然后使用
SUBSTRING_INDEX
两次以使用在FIND_IN_SET
提取的位置获取字符串。 Finally at the end HAVING
to get only the tag you're looking for.最后,在结束
HAVING
只得到你要寻找的标签。
Further demo here : https://www.db-fiddle.com/f/joDa7MNcQL2RakTgBa7qBM/3进一步演示: https : //www.db-fiddle.com/f/joDa7MNcQL2RakTgBa7qBM/3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.