我有以下查询
SELECT nature_images.image_code,
nature_objects.name
FROM nature_images
LEFT JOIN nature_objects
ON nature_images.object_id = nature_objects.id
AND nature_images.approved = 1
ORDER BY RAND()
LIMIT 0,5
结果是返回重复的nature_object.ids但是具有不同的nature_objects.id,我基本上需要的是nature_object.id在返回的每一行中都是唯一的,并且不会重复。 我尝试使用SELECT DISTINCT,但似乎失败了..无论如何都要这样做吗?
答案 0 :(得分:2)
您可以对对象名称执行GROUP BY
并获取最大代码或最少代码。
SELECT MAX(nature_images.image_code),
nature_objects.name
FROM nature_images
LEFT JOIN nature_objects
ON nature_images.object_id = nature_objects.id
AND nature_images.approved = 1
GROUP BY nature_objects.name
ORDER BY RAND()
LIMIT 0,5