sql >> Database >  >> RDS >> Mysql

Hoe schrijf je deze SQL-instructie?

SELECT user.name, user.subject
FROM user
INNER JOIN (
    SELECT name, COUNT(1) AS occurrences
    FROM user
    GROUP BY name
  ) AS user_occurrences
  ON user.name = user_occurrences.name
ORDER BY user_occurrences.occurrences DESC, user.name ASC, user.subject ASC
LIMIT 4

bewerken Dit kan beter presteren, afhankelijk van het RDBMS dat u gebruikt en de grootte van de dataset. Probeer beide en vergelijk.

SELECT user.name, user.subject
FROM user
INNER JOIN user AS user_occurrences
  ON user.name = user_occurrences.name
GROUP BY user.name --, user.subject Second GROUP BY not needed on MySQL, but it should logically be there
ORDER BY COUNT(user_occurrences.subject) DESC, user.name ASC, user.subject ASC
LIMIT 4


  1. Waarom werkt SQLAlchemy uitvoeren Update niet?

  2. Vermijd duplicaten in INSERT INTO SELECT-query in SQL Server

  3. MySQL versus PostgreSQL? Welke moet ik kiezen voor mijn Django-project?

  4. Android Realm Handling Primaire sleutel in relationeel object