SQL >> Database >  >> RDS >> Mysql

Sorteren op basis van een andere tabel in MySQL

Er zijn twee sorteerrichtingen: oplopend en aflopend. Die had je niet genoemd, dus hier zijn beide, met twee varianten.

Oplopend

SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.product_id ASC, table2.volgnr ASC;

Aflopend

SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.product_id DESC, table2.volgnr DESC;

Eerst op volgnr, dan op product_id

Oplopend:

SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.volgnr ASC, table2.product_id ASC;

Aflopend:

SELECT DISTINCT table1.*
FROM table1
INNER JOIN table2 ON table1.product_id = table2.product_id
GROUP BY table1.product_id
ORDER BY table2.volgnr DESC, table2.product_id DESC;

De queries zijn aangepast zodat er geen dubbele rijen in het resultaat staan; GROUP BY doet dat hier. In MySQL 8 kun je DISTINCT en GROUP BY vaak vervangen door een windowfunctie als je extra kolommen nodig hebt.

  1. MySQL DELETE met ORDER BY en LIMIT

  2. Eén MySQL-tabel vanuit een andere tabel bijwerken

  3. MySQL joins en COUNT(*) uit een andere tabel

  4. Een MySQL-tabel bijwerken met gegevens uit een andere tabel