我尝试创建一个脚本,循环显示与1个项目匹配的5个项目,然后显示与5个项目中的每个项目相关联的一个图像。
这是我创建的一个小提琴来说明我的问题。
http://sqlfiddle.com/#!2/17d66/1/0
我想从每个匹配的项目中选择一张图片。这是我提出的代码,但到目前为止它没有用。我使用了两个比较点,一个标签和一个系列。与产品类型和系列相关联的标签是它所属的类别。例如,iPhone 4将具有用于标签的智能手机和用作家庭的iPhone 4。任何帮助将不胜感激,我的代码如下。
<?php
// main product
$images = "SELECT img_id FROM product_images WHERE img_tag = '$p_type' && img_family = '$p_family' LIMIT 5";
$img_list = mysql_query($images);
while($rows = mysql_fetch_array($img_list)) {
$img_name = $rows['img_name'];
$img_tag = $rows['img_tag'];
$img_family = $rows['img_family'];
$img_id = $rows['img_id'];
//echo $img_name;
<div>
<img src="view.php?h=400&w=400&imgid=<?php echo $img_id; ?>" />
</div>
}
</div>
</div>
<div id="left_other">
<div class="titleHeaders">Other matching items:</div>
<?php
$match_items = "SELECT id,product_name,product_type FROM product_list WHERE name_family = '$p_family' AND id <> '$id' LIMIT 5";
$match_q = mysql_query($match_items);
$count = mysql_num_rows($match_q);
if($count > 0) {
//get matching products
while($items = mysql_fetch_array($match_q)) {
$id = ($items['id']);
echo "<p>$id</p>";
$p_name = ($items['product_name']);
echo "<p>$p_name</p>";
$type = ($items['product_type']);
echo "<p>$type</p>";
$full = "$p_name $type";
echo "<p>$full</p>";
//get photos
$other_photos = "SELECT * FROM product_images WHERE img_family = '$p_family' AND img_tag <> '$p_type' LIMIT 1";
echo $other_photos;
$other_q = mysql_query($other_photos);
while($pictures = mysql_fetch_array($other_q)) {
echo "<p>----------------------</p>";
$theid = ($pictures['img_id']);
echo "<p>$theid</p>";
$photo = ($pictures['img_name']);
echo "<p>$photo</p>";
$thetype = ($pictures['img_tag']);
echo "<p>$thetype</p>";
echo "<p>----------------------</p>";
if($photo != $newname && $theid != $newid){
if ($photo == '') {
$poly = 'images/pph.jpg';
//echo $poly;
}else{
$poly = 'product_images/regular_images/'.$photo;
//echo $poly;
} // end if
$newname = $photo;
$newid = $theid;
}else{
echo "<p>The photo name is the same!</p>";
}
答案 0 :(得分:1)
您可以使用单个查询来获取结果。这是你如何做到的。
SELECT
pl.id,
pl.product_name,
pl.product_type ,
pi.product_images
FROM product_list AS pl
LEFT JOIN (SELECT product_list_id , product_images FROM product_images LIMIT 1) AS `pi` ON pi.product_list_id = pl.id
WHERE pl.img_tag = '$p_type' AND pl.img_family = '$p_family'
LIMIT 5
但如果有一些表格结构,样本数据和所需的输出,那将是更好的。
修改
尝试此查询,您可以在最后放置
SELECT
*
FROM
`products` AS p
LEFT JOIN (SELECT MAX(img_id), img_name, img_tag, img_family FROM `images`) AS i ON i.img_family = p.`p_family` AND i.img_tag = p.`p_tag` ;
编辑
SELECT *
FROM `products` AS p
LEFT JOIN images as i
ON i.img_family = p.`p_family`
group by p.p_name;