MySQL LEFT JOIN从一个表中选择all,然后从另一个表中选择所有匹配的记录

时间:2016-02-01 07:59:37

标签: mysql left-join

我正在尝试从我的文章表中选择与几个可能变量匹配的所有记录。这总是按预期工作但现在,对于每个结果,我想从我的图像表中选择图像id与文章ID匹配的记录。

public static function getList( $headingId=null, $groupId=null, $subId=null, $query=null ) {
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$headingClause = $headingId ? "WHERE articles.headingId = :headingId" : "";
$groupClause = $groupId ? "AND articles.groupId = :groupId OR articles.group2Id = :groupId OR articles.group3Id = :groupId" : "";
$subClause = $subId ? "AND articles.subId = :subId OR articles.sub2Id = :subId OR articles.sub3Id = :subId" : "";
$searchClause = $query ? "AND articles.title LIKE '%" . $query . "%' OR articles.summary LIKE '%" . $query  ."%' OR articles.content LIKE '%" . $query  ."%'" : "";
$sql = "SELECT * FROM articles LEFT JOIN images ON articles.imageId = images.id $headingClause $groupClause $subClause $searchClause";

$st = $conn->prepare( $sql );
if ( $headingId ) $st->bindValue( ":headingId", $headingId, PDO::PARAM_INT );
if ( $groupId ) $st->bindValue( ":groupId", $groupId, PDO::PARAM_INT );
if ( $subId ) $st->bindValue( ":subId", $subId, PDO::PARAM_INT );
$st->execute();
$list = array();

while ( $row = $st->fetch() ) {
  $article = new Article( $row );
  $list[] = $article;
}

$conn = null;
return ( array ( "results" => $list ) );

}

我从中得不到任何结果。我还能尝试什么?

更新:我已经发现表中重复的列名是冲突的。此查询给出了结果,但除了第一个图像之外的所有图像都显示错误。

$headingClause = $headingId ? "AND articles.headingId = :headingId" : "";
$groupClause = $groupId ? "AND articles.groupId = :groupId OR articles.group2Id = :groupId OR articles.group3Id = :groupId" : "";
$subClause = $subId ? "AND articles.subId = :subId OR articles.sub2Id = :subId OR articles.sub3Id = :subId" : "";
$searchClause = $query ? "AND articles.title LIKE '%" . $query . "%' OR articles.summary LIKE '%" . $query  ."%' OR articles.content LIKE '%" . $query  ."%'" : "";
$sql = "SELECT articles.*, images.file FROM articles LEFT OUTER JOIN images ON articles.imageId = images.id $headingClause $groupClause $subClause $searchClause";

我只需要图像表中的一个字段,我不需要其他字段来匹配查询变量。

0 个答案:

没有答案