从每个GROUP BY(unique_id)和ORDER BY号

时间:2016-03-08 12:37:23

标签: mysql

我有id,unique_id和order_number的表。

  1. 我想通过unique_id
  2. 来分组行
  3. 我想从每个组中获取MAX id行
  4. 最后我想通过order_number
  5. 对行进行排序

    我也有很少的WHERE条款。这是我的尝试不起作用:

    SELECT MAX(id) AS id
         , order_number
      FROM table 
     WHERE final = 0 
       AND username = '$username' 
       AND active = 1 
     GROUP 
        BY unique_id 
     ORDER 
         BY order_number
    

2 个答案:

答案 0 :(得分:20)

您可以将查询用作子查询:

if(username==null || password==null){

          response.sendRedirect("Fail.jsp");
          return;
}
if (username!=null && username.equals(user)&& password.equals(pass))
        {
            response.sendRedirect("Welcome.jsp");
          return;

        }
        else {
          response.sendRedirect("Fail.jsp");
          return;
        }

或者,如果SELECT * FROM table WHERE id IN (SELECT MAX(id) AS id FROM table WHERE final=0 AND username='$username' AND active=1 GROUP BY unique_id) ORDER BY order_number 不唯一,请使用id

JOIN

答案 1 :(得分:2)

试试这个:

SELECT id, redni_broj 
FROM table 
WHERE final=0 AND username='$username' AND active=1 AND
    id IN (
              SELECT MAX(id) FROM table table2
              WHERE table.unique_id = table2.unique_id
          )
GROUP BY unique_id 
ORDER BY order_number;