简体   繁体   中英

Get array of unique elements from Mysql

I have such query:

SELECT id, forum_theme, owner, enter_time, main_topic 
FROM forum_message 
WHERE main_topic IN (1,2,3)
ORDER BY enter_time DESC
LIMIT 3 

Array is changing, and I'm adding it in java, so LIMIT equals size of array. Problem is - I need every record unique by main_topic, so each element of array must have only one record, but instead I'm having 1, 2, 2 topic records, etc.

How can I change my query to maki it possible?

In SQL Use distinct keyword to select main_topcs as follows:

SELECT id, forum_theme, owner, enter_time, main_topic 
FROM forum_message 
WHERE main_topic IN ( select distinct (main_topic) from forum_message)
ORDER BY enter_time DESC

Note: Remember if you put id or others columns they you will get more than one main_topcs

Try this:

SELECT id, forum_theme, owner, enter_time, main_topic 
FROM forum_message 
WHERE main_topic IN (1,2,3)
GROUP BY main_topic
ORDER BY enter_time DESC
LIMIT 3 

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