4

I'm trying to retrieve the "Best" possible entry from an SQL table.

Consider a table containing tv shows: id, title, episode, is_hidef, is_verified eg:

id title         ep hidef verified
1  The Simpsons  1  True  False
2  The Simpsons  1  True  True
3  The Simpsons  1  True  True
4  The Simpsons  2  False False
5  The Simpsons  2  True  False

There may be duplicate rows for a single title and episode which may or may not have different values for the boolean fields. There may be more columns containing additional info, but thats unimportant.

I want a result set that gives me the best row (so is_hidef and is_verified are both "true" where possible) for each episode. For rows considered "equal" I want the most recent row (natural ordering, or order by an abitrary datetime column).

3  The Simpsons  1  True  True
5  The Simpsons  2  True  False

In the past I would have used the following query:

SELECT * FROM shows WHERE title='The Simpsons' GROUP BY episode ORDER BY is_hidef, is_verified

This works under MySQL and SQLite, but goes against the SQL spec (GROUP BY requiring aggragates etc etc). I'm not really interested in hearing again why MySQL is so bad for allowing this; but I'm very interested in finding an alternative solution that will work on other engines too (bonus points if you can give me the django ORM code for it).

Thanks =)

6
  • "bonus points if you can give me the django ORM code for it" What kind of bonus are we talking? Jan 17, 2011 at 6:11
  • 1
    My undying thanks? Seriously tho: there is no real reward :p
    – Tyris
    Jan 17, 2011 at 6:16
  • I don't think there is way - without using a JOIN - to tell the DB Engines that allow this kind of grouping, what random row you want. Jan 17, 2011 at 6:24
  • I don't mind a solution that uses a join. I'm hoping for a solution that does not use GROUP BY though (or if it does, then for it to comply with the SQL spec).
    – Tyris
    Jan 17, 2011 at 6:27
  • is this for SQL(T-Sql) or MySql?
    – Andrew
    Jan 17, 2011 at 6:36

2 Answers 2

3

In some way similar to Andomar's but this one really works.

select C.*
FROM
(
    select min(ID) minid
    from (
        select distinct title, ep, max(hidef*1 + verified*1) ord
        from tbl
        group by title, ep) a
    inner join tbl b on b.title=a.title and b.ep=a.ep and b.hidef*1 + b.verified*1 = a.ord
    group by a.title, a.ep, a.ord
) D inner join tbl C on D.minid = C.id

The first level tiebreak converts bits (SQL Server) or MySQL boolean to an integer value using *1, and the columns are added to produce the "best" value. You can give them weights, e.g. if hidef > verified, then use hidef*2 + verified*1 which can produce 3,2,1 or 0.

The 2nd level looks among those of the "best" scenario and extracts the minimum ID (or some other tie-break column). This is essential to reduce a multi-match result set to just one record.

In this particular case (table schema), the outer select uses the direct key to retrieve the matched records.

5
  • Thanks for the answer cyberkiwi. I've gone with Andomar's answer for now but your weighting method may come in useful in the future. If I could rate this post up I would... but I don't have enough rep =(
    – Tyris
    Jan 17, 2011 at 11:40
  • @Andomar - The part that says "LIMIT 1". The question was about "...works under MySQL and SQLite, but goes against the SQL spec..." so I thought an ANSI SQL92 compliant solution was sought. LIMIT isn't Jan 17, 2011 at 11:43
  • I didn't realise LIMIT wasn't standards compliant =( .. I might have a bit more of a play around with both solutions. Since LIMIT is supported in all the databases I'm likely to ever use this with I may go with that one. Thanks for the info =)
    – Tyris
    Jan 17, 2011 at 22:57
  • @cyberkiwi: Yeah, my answer says it's not standards compliant. I don't know of a way to resolve ties within the SQL Standard. Your solution doesn't (i.e. it will repeat rows 2 and 3)
    – Andomar
    Jan 18, 2011 at 6:18
  • @cyberkiwi: Cool, didn't see that. I'll upvote your answer, but please consider a less snarky style of commenting ;)
    – Andomar
    Jan 18, 2011 at 9:31
1

This is basically a form of the groupwise-maximum-with-ties problem. I don't think there is a SQL standard compliant solution. A solution like this would perform nicely:

SELECT  s2.id
,       s2.title
,       s2.episode
,       s2.is_hidef
,       s2.is_verified
FROM    (
        select  distinct title
        ,       episode
        from    shows
        where   title = 'The Simpsons' 
        ) s1
JOIN    shows s2
ON      s2.id = 
        (
        select  id
        from    shows s3
        where   s3.title = s1.title
                and s3.episode = s1.episode
        order by
                s3.is_hidef DESC
        ,       s3.is_verified DESC
        limit   1
        )

But given the cost of readability, I would stick with your original query.

3
  • Looks workable... I'll have a look at the article later tonight too. Any idea what the performance difference (positive or negative) compared to my query might be? I'll have a play with this one when I get the chance accept your answer then.
    – Tyris
    Jan 17, 2011 at 6:44
  • The link you provided was really helpful and I've fashioned a solution out of your post and the link. I'll have to use raw() in django, but thats fine I guess.
    – Tyris
    Jan 17, 2011 at 11:39
  • @Andomar : This works for me. But thinking interns of performance, this is too heavy. Taking lot of time to execute for 45 records over the 'Group By'. Is there any way that we can optimize the above query?
    – Jagadeesh
    Apr 21, 2015 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.