我想有我查询我的数据库返回的每个记录一次,问题是,如果上市具有存储在它返回的多个记录一个单独的表中(每个图像)php sql查询为每个单独的记录返回多行,滥用连接?
这里多张图片是一个片段我的数据库布局(包裹在**的数据是主键)
tbl_listings => **listingID**,title,description,dateListed
tbl_images => **imageID**,filename
tbl_listing_image => **listingID**,**imageID**
这是我的代码
$stmt = $db->stmt_init();
if($stmt->prepare("SELECT l.listingID, l.title, l.description, l.dateListed, c.category, tn.townID, tn.town, i.filename
FROM tbl_listings AS l
LEFT JOIN tbl_listing_category AS lc ON lc.listingID = l.listingID
LEFT JOIN tbl_category AS c ON c.categoryID = lc.categoryID
LEFT JOIN tbl_listing_type AS lt ON lt.listingID = l.listingID
LEFT JOIN tbl_type AS t ON t.typeID = lt.typeID
LEFT JOIN tbl_listing_town AS ltn ON ltn.listingID = l.listingID
LEFT JOIN tbl_towns AS tn ON tn.townID = ltn.townID
LEFT JOIN tbl_listing_image AS li ON li.listingID = l.listingID
LEFT JOIN tbl_images AS i ON i.imageID = li.imageID
WHERE t.typeID =?"))
{
$type = 1;
$stmt->bind_param("i",$type);
$stmt->execute();
$stmt->bind_result($id,$title,$desc,$date,$cat,$townID,$town,$image);
echo "<ul>";
while($stmt->fetch())
{
$img = "images/listing/$id/$image";
echo "<li><img src='$img' alt='$title' title='$title'>#".$id."<h4>" . $title . "</h4>" . $desc . "<br /><strong> Category:</strong> " . $cat . " - <strong>Location: </strong> - <strong> Posted On:</strong> " . date("i M Y",$date) . "</li><hr>";
}
echo "</ul>";
$stmt->close();
返回以下结果(考虑有在tbl_listings只有1个记录表)
listingID title description dateListed category townID town filename
1 listing 1 listing desc 1411240751 teaching 11 town a image1.jpg
1 listing 1 listing desc 1411240751 teaching 11 town a image2.jpg
1 listing 1 listing desc 1411240751 teaching 11 town a image3.jpg
所以查询将返回3条记录(每个文件名),即使其上市时相同
,所以我尝试添加一个GROUP BY l.listingID到我的查询返回其只有一个记录,但它也只返回了,像这样
listingID title description dateListed category townID town filename
1 listing 1 listing desc 1411240751 teaching 11 town a image1.jpg
所以我的问题是每个上市我怎么只能返回1分的纪录,但它的所有相关图像的第一形象?我是否需要在while循环中运行一个单独的查询来获取图像?
希望得到任何帮助 干杯
请参阅GROUP_CONCAT(expr)MySQL分组函数。对不起,你的SQL有点长,可以用一个我可以肯定它是正确的例子来写答案。其他人? – 2014-09-24 22:46:30
@ kiko软件,感谢您的回复我会检查出来。 – user2886669 2014-09-24 22:50:00