1

I made the following query that get the MIN(id) of duplicate path values in the table movies:

SELECT m.id, m.user_id , m.path
FROM movies m
  INNER JOIN (
               SELECT Min(id) as movie_id, path,  COUNT(*)
               FROM movies
               WHERE importer LIKE '%AS%'
               GROUP BY  path
               HAVING COUNT(*) > 1) temp
    ON  temp.path = p.path
        AND temp.movie_id = m.id
        AND importer LIKE '%AS%'

I got this result:

  id       | user_id |     path    | 
­­­­­­­­­­­­------------------------------------
 2         | 1234    |     XXXX    |  
 8         | 4231    |     BBBB    | 

The problem is that I have another movie with the same path but dont appear because the MIN() and the GROUP BY path

I want to group the path but dont exlude the other path because I do MIN(id)

This is the expected result:

  id       | user_id |     path    | 
­­­­­­­­­­­­------------------------------------
 2         | 1234    |     XXXX    |  
 8         | 4231    |     BBBB    | 
 5         | 3421    |     BBBB    | 

What Im doing wrong?

@Tim Biegeleisen

The problem is with that query I obtain duplicated paths with same user_id :

  id       | user_id |     path    | 
­­­­­­­­­­­­------------------------------------
  3523        12287         asd
  3524        12287         asd
  3525        12287         asd

I should obtain the min id for each grouped path.

4
  • 1
    Surely you would want temp.importer to equal p.importer!! Beyond that, see meta.stackoverflow.com/questions/333952/… Commented Feb 7, 2017 at 16:21
  • DISTINCT (user_id)? Commented Feb 7, 2017 at 16:24
  • Please show us sample data if possible. Commented Feb 7, 2017 at 16:24
  • @user3741598 Be aware that DISTINCT is not a function - it takes no arguments. Commented Feb 7, 2017 at 16:34

1 Answer 1

1

I think what you want to do is to GROUP BY the user_id and path, and then choose the record having the smallest movie ID, should there be multiple users associated with a given path. If so, then the following query should work:

SELECT m1.id, m1.user_id, m1.path
FROM movies m1
INNER JOIN
(
    SELECT user_id, path, MIN(id) AS min_id
    FROM movies
    WHERE importer LIKE '%AS%'
    GROUP BY user_id, path
) m2
    ON m1.path    = m2.path AND
       m1.user_id = m2.user_id AND
       m1.id      = m2.min_id
Sign up to request clarification or add additional context in comments.

2 Comments

@devtreat I updated my answer. I think you want to GROUP BY the user ID and path, and then retain the record with the minimum ID.
This query made what I wanted. Thank you very much!

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.