简体   繁体   中英

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(' ', $_POST['tag']);

Assuming that I have table named product with row named tags with 3 different values that inserted inside like this:

usb adapter charger

I have tried using this method using like operator ( % ), but that didn't worked.

$sql = "SELECT * FROM product WHERE tags='%usb%'";

How can I extract only one value from the imploded array using WHERE in mysql query?

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. 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:

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. Then with SUBSTRING_INDEX twice to get the string using the location extracted in FIND_IN_SET . Finally at the end HAVING to get only the tag you're looking for.

Further demo here : https://www.db-fiddle.com/f/joDa7MNcQL2RakTgBa7qBM/3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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