lummycoder
lummycoder

Reputation: 608

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?

Upvotes: 0

Views: 191

Answers (2)

vicentazo
vicentazo

Reputation: 1799

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 

Upvotes: 1

Shamim Ahmmed
Shamim Ahmmed

Reputation: 8383

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

Upvotes: 1

Related Questions