Query MYSQL does not order correctly

Asked

Viewed 44 times

0

Hello. I have the following query:

    SELECT * 
      from usuarios_cursos_matriculados 
 LEFT JOIN cursos ON cursos.cedoc_doc_id_fk = usuarios_cursos_matriculados.cedoc_doc_id_fk 
 LEFT JOIN cedoc_doc ON cedoc_doc.cedoc_doc_id = cursos.cedoc_doc_id_fk 
 LEFT JOIN cursos_aulas ON cursos.cedoc_doc_id_fk = cursos_aulas.cedoc_doc_id_fk 
 LEFT JOIN (SELECT * FROM ultimas_aulas order by data_realizada DESC) AS c ON c.id_curso = cedoc_doc.cedoc_doc_id 
  GROUP BY cursos_aulas.cedoc_doc_id_fk DESC

In this case, the table should pull the courses in which the user is enrolled contained in the table usuarios_cursos_matriculados, the first class of the course, contained in the table cursos_aulas and the last class viewed, contained in the table last lessons. The query is working in half, it correctly pulls the courses enrolled and the first class of each course, however, it does not correctly sort the last lessons viewed by the user in the selected courses. Instead of ordering it in descending order according to the column data_realizada, which contains the date on which the date was viewed, it orders in ascending order. When I remove group by, it orders correctly, however, records get duplicated.

How could I fix the operation of this query?

  • I believe that here: GROUP BY cursos_aulas.cedoc_doc_id_fk DESC you skipped the ORDER BY clause`.

  • Is the query correct? Only the order that is wrong? You want only the last class or all ordered?

1 answer

1

You should add the Order by enclosure at the end of the query follows how it would look:

    SELECT * 
      from usuarios_cursos_matriculados 
 LEFT JOIN cursos ON cursos.cedoc_doc_id_fk = usuarios_cursos_matriculados.cedoc_doc_id_fk 
 LEFT JOIN cedoc_doc ON cedoc_doc.cedoc_doc_id = cursos.cedoc_doc_id_fk 
 LEFT JOIN cursos_aulas ON cursos.cedoc_doc_id_fk = cursos_aulas.cedoc_doc_id_fk 
 LEFT JOIN (SELECT * FROM ultimas_aulas order by data_realizada DESC) AS c ON c.id_curso = cedoc_doc.cedoc_doc_id 
  GROUP BY cursos_aulas.cedoc_doc_id_fk DESC
  ORDER BY c.data_realizada DESC
  • In this way he even orders by date, but still pulls the first record of each course, instead of the last.

  • You can add more order by in sequence, e.g.: in this case was: ORDER BY c.data_performed DESC Voce can be added with a comma, thus: ORDER BY c.data_performed, (another column to order), (another one if you like), (Etc) DESC

Browser other questions tagged

You are not signed in. Login or sign up in order to post.