MySQL 结果从“Product”表返回重复的产品,因为“Images”表下的多个项目具有相同的“image.id_node”值。我可以通过什么方式编辑它,以便它只为每个相应的“image.id_node”返回一个产品?最好是找到 ID 值最高的那个?
"SELECT *
FROM `product`
left join image
on product.id_node = image.id_node
WHERE `product_publish` = 1
AND image.main = 1
AND `product_type_item`=$type_item
AND product_status = 1
order by product_position ASC;"
You can use a subquery for this, which determines the max(product.id)
per id_node
.
select *
from (
select max(id) id
from `product`
group by `id_node`
) q
inner join `product` p
on q.id = p.id
left join image i
on p.id_node = i.id_node
where `product_publish` = 1
and i.main = 1
and `product_type_item` = $type_item
and product_status = 1
order by product_position asc
i doubt that query performs as you expect - at least not reliably.. the where clause is entirely redundant.