简体   繁体   中英

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. I tried using SELECT DISTINCT but that seems to fail.. Is there anyway to do that?

you can do a GROUP BY on object name and get maximum code or minimum code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM