[英]How to make sure that a field in SQL query is unique?
I have the following query 我有以下查询
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
The result is returning repeated nature_object.ids but with different nature_objects.id, what I basically need is that the nature_object.id is unique in every row returned and doesn't get repeated. 结果是返回重复的nature_object.id,但是具有不同的nature_objects.id,我基本上需要的是nature_object.id在返回的每一行中都是唯一的,并且不会重复。 I tried using SELECT DISTINCT but that seems to fail.. Is there anyway to do that? 我尝试使用SELECT DISTINCT,但这似乎失败了。
you can do a GROUP BY
on object name and get maximum code or minimum code. 您可以对对象名称执行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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.