在mysql查询中使用MIN()的问题

时间:2017-02-07 16:16:57

标签: mysql

我做了以下查询,以获取表MIN(id)path个重复的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%'

我得到了这个结果:

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

问题是我有另一部电影路径相同,但没有出现因为MIN()GROUP BY path

我想对路径进行分组,但不要排除其他路径,因为我MIN(id)

这是预期的结果:

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

我做错了什么?

@Tim Biegeleisen

问题在于该查询我获得了具有相同user_id的重复路径:

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

我应该获得每个分组路径的最小ID。

1 个答案:

答案 0 :(得分:1)

我认为您要做的是GROUP BY user_id path,然后选择电影ID最小的记录,是与给定path关联的多个用户。如果是这样,那么以下查询应该有效:

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