1

次のようなデータを含むテーブルがあります。

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;

すべて問題ないようですが、フィールドにauthorはコンマで区切られた数人の著者が含まれている可能性があるため、フィルターauthor IN ('author1')は機能しません。関連するすべての記事を選択する方法author1(この場合は最初と 2 番目のレコード)?

4

4 に答える 4

2

データベース構造を変更する必要があると思います。文字列を介した検索は遅い (っぽい) ので、今はうまくいくかもしれませんが、データセットが増えると、これが面倒になります。

私はこのようなものが良いだろうと思います:

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 は book 1&2 を書き、author2 は book 2 を書きました。

長期的にはより柔軟です。適切なデータベース構造は、最初から非常に重要です

于 2013-08-02T09:09:16.470 に答える
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;
}

完璧にはほど遠いですが、うまくいくはずです。

于 2013-08-02T09:09:45.000 に答える
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%';

これがリファレンス検索セットです

于 2013-08-02T09:14:25.620 に答える
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;



?>
于 2013-08-02T09:07:22.333 に答える