我尝试列出所有带有产品图片的产品,但不确定如何在这种情况下使用subquery
。以下是我的数据库结构
产品
products_id + product_name +
1 | Apple |
2 | Banana |
products_screenshot
products_id + images +
1 | Apple-1.jpg |
1 | Apple-2.jpg |
1 | Apple-3.jpg |
2 | Banana-1.jpg |
2 | Banana-2.jpg |
2 | Banana-3.jpg |
这是我的疑问:
$sql = "SELECT p.* FROM `products` p ORDER BY p.products_id ASC ";
//LEFT JOIN (SELECT ps.* FROM `products_screenshot` ps WHERE ps.products_id=p.products_id) AS pss ON(p.products_id=pss.products_id)
$query = $db->query($sql);
while ($row = $query->fetch_object()) {
// result
echo $row->products_name.'</br>';
// list all product screenshot related with this
//$row->images
}
答案 0 :(得分:3)
根据您的要求,您可以执行以下操作。然后执行查询并循环。 该 $ row-&gt;图片将以逗号分隔,您可以拆分它们以显示产品。
$sql = "SELECT p.products_id,p.product_name,group_concat(pi.images) as `images`
FROM `products` p
left join products_screenshot pi on pi.products_id = p.products_id
group by p.products_id
ORDER BY p.products_id ";
如果您不关心在循环中多次重复的产品,那么只需使用下面的每个循环的位置,您将获得产品和相关图像的新行
$sql = "SELECT p.products_id,p.product_name,pi.images
FROM `products` p
left join products_screenshot pi on pi.products_id = p.products_id
ORDER BY p.products_id ";
答案 1 :(得分:1)
像这样的简单查询出了什么问题:
select
p.products_id,
p.product_name,
ps.images
from
products p
join products_screenshot ps
on p.products_id=ps.products_id
where
whateveryouline
order by
1,2
它能为您提供所需的所有物品吗?
答案 2 :(得分:0)
尝试此查询:
select products.product_name, products_screenshot.images from products,products_screenshot where products.products_id = products_screenshot.products_id
答案 3 :(得分:0)
SELECT * from products_screenshot as ps where products_id IN (SELECT p.products_id from products as p WHERE p.products_id = ps.products_id )