php - 我如何使用 php 数组作为值在 mysql 表上运行查询

标签 php mysql sql arrays

我有一个包含用户兴趣记录的 mysql 表。例如

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

在上面的示例中,假设我正在搜索对娱乐感兴趣的用户的记录,并且用于查询数据库的值包含数组值。例如

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

有了那个数组,我应该可以得到 lynx 记录,因为他们对娱乐感兴趣。 我试过对 MySQL 使用 IN 运算符,但没有得到任何结果。我还将该字段转换为全文,只是为了使用 LIKE 运算符,但也没有得到任何结果。

最佳答案

短期解决方案

interest 数据是非规范化的,因此您正在考虑使用 FIND_IN_SET operator搜索它:

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

@interest 表示您发布的数组中的单个值。即:“娱乐”

长期解决方案

表需要重组为规范化数据 - 这意味着将 interests 移出 USERS 表,使用:

USER_INTERESTS

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

兴趣

  • interest_id(主键)
  • 描述

这是您在这种情况下使用的查询:

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

基于多个兴趣进行搜索:

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)

关于php - 我如何使用 php 数组作为值在 mysql 表上运行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5606520/

相关文章:

php - 的PHP,MySQL的错误 undefined index

mysql - MySQL 触发器中的事务 ID

sql - 从字符串转换日期和/或时间时转换失败

php - 从 Trello 身份验证中获取 "App not found"

php - 使用 PHP Mail() 发送附件?

php - MySQL php get column using another column(使用用户名获取密码)

c# - SQL Server 中的逗号分隔操作

php - 在mysql数据库中插入和获取不同的语言

php - 如何在mysql数据库中存储数据对?

PHP exec() 和路径中的空格