Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

MySQL 5.7.5+ dapatkan baris pertama untuk grup

ORDER BY di subquery tabel turunan diabaikan di MySQL 5.7.

Lihat https://dev.mysql.com/ doc/refman/5.7/en/derived-table-optimization.html

Kueri luar Anda memiliki JOIN dan GROUP BY, sehingga tidak memenuhi syarat untuk menyebarkan ORDER BY, oleh karena itu mengabaikan ORDER BY.

Perilaku pengoptimal ini dikendalikan oleh sakelar pengoptimal derived_merge . Anda dapat menonaktifkannya.

Demo:

mysql [localhost] {msandbox} (test) > select @@version;
+-----------+
| @@version |
+-----------+
| 5.7.21    |
+-----------+

mysql [localhost] {msandbox} (test) > SELECT     columnPrimaryKey,     column1,     column2,     column3 FROM     (SELECT         columnPrimaryKey,         column1,         column2,         column3     FROM testTable     ORDER BY column2 ) AS tbl GROUP BY column3;
+------------------+----------------+---------+---------+
| columnPrimaryKey | column1        | column2 | column3 |
+------------------+----------------+---------+---------+
|                1 | Some Name 8-4  |       4 |       8 |
|                6 | Some Name 9-1  |       1 |       9 |
|                8 | Some Name 10-2 |       2 |      10 |
+------------------+----------------+---------+---------+

mysql [localhost] {msandbox} (test) > set optimizer_switch = 'derived_merge=off';
Query OK, 0 rows affected (0.00 sec)

mysql [localhost] {msandbox} (test) > SELECT     columnPrimaryKey,     column1,     column2,     column3 FROM     (SELECT         columnPrimaryKey,         column1,         column2,         column3     FROM testTable     ORDER BY column2 ) AS tbl GROUP BY column3;
+------------------+----------------+---------+---------+
| columnPrimaryKey | column1        | column2 | column3 |
+------------------+----------------+---------+---------+
|                5 | Some Name 8-1  |       1 |       8 |
|                6 | Some Name 9-1  |       1 |       9 |
|                8 | Some Name 10-2 |       2 |      10 |
+------------------+----------------+---------+---------+



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara memasukkan data dalam model kumpulan bersarang (MySQL);

  2. BERBEDA ON di django

  3. Django + MySQL - Encoding tidak dikenal:utf8mb4

  4. Kesalahan acak:#1045 Tidak dapat masuk ke server MySQL

  5. Kapan menambahkan indeks apa dalam tabel di Rails