php - 通过发布的数组过滤数据?

标签 php mysql sql database arrays

我有一个包含这样数据的表:

articles. id   | author                | title     | content  | type
             1 | author1, author2      | thetitle1 | text1    | typeA
             2 | author1               | thetitle2 | text2    | typeB
             3 | author2               | thetitle3 | text3    | typeA

Posted array 是一个过滤器:

$conditions = array();
$where = '';

if(isset($_POST['authors'])){ //empty, is_array and etc.
  $authors = $_POST['authors']; // [ author1, author2 ]
  $conditions[] = "author IN ('".implode("','",$authors)."')";
}
if(isset($_POST['types'])){
  $types = $_POST['types']; // [ typeA, typeB ]
  $conditions[] = "type IN ('".implode("','",$types)."')";
}

if(!empty($conditions)){
  $where = ' WHERE '.implode(' AND ', $conditions);
}

$sql = "SELECT * FROM articles".$where;

似乎一切正常,但字段 author 可以包含几个作者,用逗号分隔,因此过滤器 author IN ('author1') 将不起作用。如何选择所有涉及author1的文章(本例为第一条和第二条记录)?

最佳答案

我认为您需要更改数据库结构。通过字符串搜索很慢(差不多),这现在可能可行,但当数据集增加时,这将成为一种拖累。

我认为像这样的东西会更好:

author
--------
id  name  
1   author1
2   author2

books:
--------
id  title  
1   Some Book  
2   Some Other Book  

author_book:
--------
id  author_id  book_id
1     1         1
2     1         2
3     2         2

在我的例子中,作者 1 写了书 1 和 2,作者 2 写了书 2 另一个是:第 1 本书由作者 1 撰写,第 2 本书由作者 1 和 2 撰写

从长远来看,它更加灵活。开始时正确的数据库结构非常重要

关于php - 通过发布的数组过滤数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18012723/

相关文章:

mysql - 计算cakephp 3.x中数据库记录的总价

python - 使用 Django 选择不在另一个表中的值

php - 如何按月份和用户名对每个月的总行求和

php - WHERE 子句日期大于 24 小时 - Carbon/Laravel

php - 使用 fnmatch() 测试 level1.level2.level3 中的权限

python - 类型错误 : float() argument must be a string or a number, 而不是 'NaTType'

python - DataFrame 列中的每个项目都是不同维度的列表 - 如何进行?

sql - 获取每 3 天组取 1 次的发生次数

sql - Postgres/ANSI SQL 系统如何将 'count' 聚合与 GROUP BY 字段相关联

php - laravel 5 中间件中的条件始终为 false