How to select DISTINCT rows without having the ORDER BY field selected

前端 未结 6 970
我寻月下人不归
我寻月下人不归 2021-01-06 15:49

So I have two tables students (PK sID) and mentors (PK pID). This query

SELECT s.pID
FROM students s JOIN mentors m ON s.pID = m.pID
WHERE m.tags LIKE \'%a%\         


        
相关标签:
6条回答
  • 2021-01-06 16:34

    After using distinct "ORDER BY s.sID DESC;" will not work so try using somwthing like following

    SELECT distinct(s.pID) as PID
    FROM students s JOIN mentors m ON s.pID = m.pID
    WHERE m.tags LIKE '%a%'
    ORDER BY PID;
    

    This will return >> 3, 9, 10

    0 讨论(0)
  • 2021-01-06 16:34

    Use this

    SELECT DISTINCT s.pID as PID
    FROM students s JOIN mentors m ON s.pID = m.pID
    WHERE m.tags LIKE '%a%'
    ORDER BY s.sID DESC,1;
    
    0 讨论(0)
  • 2021-01-06 16:40
    SELECT s.pID
    FROM students s JOIN mentors m ON s.pID = m.pID   
    WHERE m.tags LIKE '%a%'
    GROUP BY s.pID
    ORDER BY MAX(s.sID) DESC
    
    0 讨论(0)
  • 2021-01-06 16:40

    You can't receive records in any predefined order if you don't use ORDER BY because then the DB engine decides in what order to return them.

    0 讨论(0)
  • 2021-01-06 16:49

    After struggling some more I have this

    SELECT s.pID, MAX(s.sID) AS newest_student
    FROM students s JOIN mentors m ON s.pID = m.pID
    WHERE m.tags LIKE '%a%'
    GROUP BY s.pID
    ORDER BY newest_student DESC;
    

    which gives me the required 9,3,10 but I have one useless field returned with it. I am hoping some-one will come with a better solution.

    0 讨论(0)
  • 2021-01-06 16:54

    Try this:

    SELECT s.pID
    FROM students s JOIN mentors m ON s.pID = m.pID
    WHERE m.tags LIKE '%a%'
    GROUP BY s.pID
    ORDER BY s.sID DESC;
    

    I.e. GROUP BY instead of DISTINCT should preserve order.

    0 讨论(0)
提交回复
热议问题