Mysql: get all distinct values from field serialized by PHP

时光毁灭记忆、已成空白 提交于 2019-12-25 23:07:31

问题


I have a movies table (has data from a legacy project) with the field genre which contains values serialized by PHP like:

a:3:{i:0;s:9:"Animation";i:1;s:9:"Adventure";i:2;s:5:"Drama";}

I'm working in a search page, & I need to find all unique genres of the current search result to be used as a filter in the page,

as an example, if the search result was these 2 movies:

  • The Dark Knight (action, crime, drama)
  • Black Knight (fantasy, adventure, comedy)

I want to know the combination of there genres, which will be:

['action', 'crime', 'drama', 'fantasy', 'adventure', 'comedy']

how to get the genres array? (I'm using Yii2).


回答1:


You should unserialize your data

$data = 'a:3:{i:0;s:9:"Animation";i:1;s:9:"Adventure";i:2;s:5:"Drama";}';
$data = unserialize($data);
print_r($data);

and you will get

Array
(
    [0] => Animation
    [1] => Adventure
    [2] => Drama
)

If you need to search the entire table for "Drama" to decide which shows/movies to display, you could always use wildcards in your search

select * from table where column like '%Drama%'

but of course make sure to take appropriate database precautions.




回答2:


Suppose you have a serialize string that have various values in different position and you need to search from serialized field. You want particular key’s value using MySQL query. It is very easy with MySQL “%like%” statement but “%like%” fetches more matches which you do not require. Search from serialized field: Suppose you have a following serialize string in database:

a:9:{s:2:"m1";s:4:"1217";s:2:"m2";s:8:"9986-961";s:2:"m3";s:19:"1988-03-07 00:00:00";s:2:"m4";s:0:"";s:2:"m5";s:0:"";s:2:"m6";s:0:"";s:2:"m7";s:3:"104";s:2:"m8";s:6:"150000";s :2:"m9";s:18:"Ok Then, Yes It Is";}

And you need the row in which the m9 value is ‘Yes It Is’.

So the sql will be like:

SELECT * FROM table WHERE field REGEXP '.*"array_key";s:[0-9]+:".array_value.".*'

test code

SELECT * FROM table WHERE field REGEXP '.*"m9";s:[0-9]+:".Ok Then, Yes It Is.".*'


来源:https://stackoverflow.com/questions/31151291/mysql-get-all-distinct-values-from-field-serialized-by-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!