我有一个包含这样数据的表:
articles. id | author | title | content | type
1 | author1, author2 | thetitle1 | text1 | typeA
2 | author1 | thetitle2 | text2 | typeB
3 | author2 | thetitle3 | text3 | typeA
已发布数组是此过滤器:
$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;
似乎所有都是okey,但字段author
可以包含一些以逗号分隔的作者,因此过滤器author IN ('author1')
将无效。如何选择涉及author1
的所有文章(在这种情况下,它是第一个和第二个记录)?
答案 0 :(得分:2)
我认为您需要更改数据库结构。通过字符串搜索很慢(ish),现在可能会有效,但是当数据集增加时,这将成为拖累。
我认为这样的事情会更好:
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
在我的例子中,author1写了第1册和第2册,而author2写了第2册 另一个是围绕:第1册由作者1撰写,book2由author1& 2
撰写从长远来看,它的灵活性更强。正确的数据库结构对于
开始非常重要答案 1 :(得分:1)
我同意@Martijn,但是如果你不能改变DB你可以尝试这样的事情:
if(isset($_POST['authors'])){ //empty, is_array and etc.
$authors = $_POST['authors']; // [ author1, author2 ]
$subC = array();
$subC [] = " ( author IN ('".implode("','",$authors)."') ) ";
foreach ($authors as $a){
$subC [] = " ( author LIKE %$a% ) " ;
}
$subC = ' ( ' . implode (' OR ' , $subC) . ' ) ';
$conditions[] = $subC;
}
这远非完美,但应该做到这一点。
答案 2 :(得分:0)
试试这个。 (http://codepad.org/wjISZj54)
<?php
$authors = array('abc','def','asd');
$types=array('type1','type2');
$authorarr=array();
foreach($authors as $author)
{
$authorarr[]="'".$author."'";
}
$authorstr=implode(',',$authorarr);
$conditions[] = "author IN ($authorstr)";
$typearr=array();
foreach($types as $type)
{
$typearr[]="'".$type."'";
}
$typestr=implode(',',$typearr);
$conditions[] = "type IN ($typestr)";
if(!empty($conditions)){
$where = ' WHERE '.implode(' AND ', $conditions);
}
echo $sql = "SELECT * FROM articles".$where;
?>
答案 3 :(得分:0)
您需要规范化您的结构,保存逗号分隔值不是您的问题的好习惯,您可以使用FIND_IN_SET
SELECT * FROM articles WHERE type IN (...) OR FIND_IN_SET("author1", author)
其他你也可以使用LIKE来匹配所需的结果,但这不是一个好主意
SELECT * FROM articles WHERE type IN (...) OR author LIKE '%author1%';
以下是参考Find in set