开发者

How can i run a query on a mysql table using php arrays as values

I have a mysql table that contains records of user's interest. e.g

id  | username |    email     | interest
-------------------------------------------------------------------
2   | lynx     | lynx@exm.com | sports, business, entertainment

W开发者_如何学编程ith the example above, assuming I'm searching for records of user's with interest in entertainment and the values used to query the database contains array values. eg

array('movies', 'games', 'entertainment'); 

With that array, i should be able to get lynx records because they are interested in entertainment. I've tried using the IN Operator for MySQL but didn't get any result. I also converted the field to fulltext just to use the LIKE operator but didn't get any results too.


Short Term Solution

The interest data is denormalized, so you're looking at using the FIND_IN_SET operator to search it:

WHERE FIND_IN_SET(@interest, t.interest) > 0

@interest represents a single value from the array you posted. IE: "entertainment"

Long Term Solution

The tables need to be restructured to be normalized data - that means moving the interests out of the USERS table using:

USER_INTERESTS

  • user_id (pk, fk to USERS.user_id)
  • interest_id (pk, fk to INTERESTS.interest_id)

INTERESTS

  • interest_id (primary key)
  • description

Here's the query you'd use in that situation:

SELECT u.*
  FROM USERS u
  JOIN USER_INTERESTS ui ON ui.user_id = u.user_id
  JOIN INTERESTS i ON i.interest_id = ui.interest_id
 WHERE i.description = @interest

To search based on multiple interests:

SELECT u.*
  FROM USERS u
  JOIN USER_INTERESTS ui ON ui.user_id = u.user_id
  JOIN INTERESTS i ON i.interest_id = ui.interest_id
 WHERE i.description IN (@interest1, @interest2, @interest3)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜