0

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?

2
  • DISTINCT from SQL side, Set from Java side ? Commented Aug 8, 2013 at 7:37
  • Which one do you want? Commented Aug 8, 2013 at 7:58

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

If I did SELECT distinct(main_topic), id, enter_time FROM forum_message WHERE main_topic IN (1,2,3,4) ORDER BY enter_time DESC LIMIT 4 I will recieve unique records, but not unique main_topic in each record - they mustn't be repeated, but if distinct(main_topic) without other fileds - it works well, I need more information in records.
See, what I need is main_topic 1 - one record, 2 - other, 3 - other, only main_topic must be unique and therefore only one record for ech topic would be. So how to do it right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.