简体   繁体   English

如何从 MySQL 行的内爆数组中提取一个值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM