views:

79

answers:

3

Hi, I'm trying to perform a DISTINCT clause on a query like this

SELECT DISTINCT username, wiki.text, wiki.date
FROM wiki_house
INNER JOIN wiki ON wiki_house.wiki_id = wiki.id
INNER JOIN users ON wiki.user_id = users.id
AND wiki_house.house_id = 1
AND wiki.language = 'it'
ORDER BY wiki.date DESC
LIMIT 10

this returns:

username     wiki.text     wiki.date
mike         Hello         2010-03-09
mike         Helo          2010-03-08
kim          Whats...      2010-03-07
mike         When in...    2010-03-06
eddy         Hel           2010-03-05

I thought this query should returned the last 10 wikis from different usernames, by the DISTINCT clause, but it simply return me the last 10 results, so if an user has wrote 2 versions of his wiki, these are showed in the page.

How can I select only the last 10 wikis from different usernames so something like this?

username     wiki.text     wiki.date
mike         Hello         2010-03-09
kim          Whats...      2010-03-07  
eddy         Hel           2010-03-05
+3  A: 

This should be possible using a subquery. The inner query orders all the rows by date, so the first instance of each username in that result would be the row you're looking for.

The outer query groups by username, and AFAIK if you're not using GROUP_CONCAT this will always take the first instance of each row containing the username.

SELECT username, wikitext, wikidate FROM
  (SELECT username, wiki.text AS wikitext, wiki.date AS wikidate
  FROM wiki_house
  INNER JOIN wiki ON wiki_house.wiki_id = wiki.id
  INNER JOIN users ON wiki.user_id = users.id
  AND wiki_house.house_id = 1
  AND wiki.language = 'it'
  ORDER BY wiki.date DESC)
GROUP BY username
LIMIT 10

If that's not working, have a look at the accepted answer for this similar question which has another solution. You should be able to modify it to suit your needs.

DisgruntledGoat
A: 
SELECT DISTINCT(username), wiki.text, wiki.date
FROM wiki_house
INNER JOIN wiki ON wiki_house.wiki_id = wiki.id
INNER JOIN users ON wiki.user_id = users.id
AND wiki_house.house_id = 1
AND wiki.language = 'it'
ORDER BY wiki.date DESC
LIMIT 10
Ervin
+1  A: 

Thanks to DisgruntledGoat I've found a solution:

SELECT username, wikitext, wikidate FROM
    (SELECT username, wiki.text AS wikitext, wiki.date AS wikidate
    FROM wiki_house
    INNER JOIN wiki ON wiki_house.wiki_id = wiki.id
    INNER JOIN users ON wiki.user_id = users.id
    AND wiki_house.house_id = 1
    AND wiki.language = 'it'
    ORDER BY wiki_house.wiki_id DESC) wiki_house
GROUP BY username
ORDER BY wiki.date DESC
LIMIT 10
Vittorio Vittori