Selecting the most popular destination of my database on mysql

Tavirio :

I've created 3 tables:

CREATE TABLE participe 
(
    IDadherent INTEGER, 
    IDsortie INTEGER, 
    CONSTRAINT pk2 PRIMARY KEY (IDadherent, IDsortie)
); 

CREATE TABLE sortie 
(
    IDsortie INTEGER PRIMARY KEY, 
    jour DATE, 
    Latitude_sortie FLOAT, 
    Longitude_sortie FLOAT
); 

CREATE TABLE adherent 
(
    IDadherent INTEGER PRIMARY KEY, 
    nom VARCHAR(30), 
    prenom VARCHAR(30)
);

TL;DR:

  • Table 1) Adherent (this is the people potentially going to a set of destinations with adherentID as a primary key)

  • Table 2) Sortie (this is the table with the potential destinations with destinationID as a primary key)

  • Table 3) Participe (this table links both primary keys: AdherentID and destinationID

If I select the content of the table "participe" I get something like this:

+----------+------------+
| IDsortie | IDadherent |
+----------+------------+
|        5 |          1 |
|        5 |          3 |
|        5 |          5 |
|        4 |          2 |
|        3 |          1 |
|        3 |          4 |
|        3 |          5 |
|        2 |          3 |
|        2 |          5 |
|        1 |          1 |
|        1 |          2 |
|        1 |          3 |
|        0 |          6 |
+----------+------------+

I've attempted to order the above table and get a new table with the most popular destinations (IDsortie), expecting to get something like this:

+----------+----------------+
| IDsortie | Numeroadherent |
+----------+----------------+
|        5 |          3     |
|        4 |          1     |
|        3 |          3     |
|        2 |          2     |
|        1 |          3     |
|        0 |          1     |
+----------+----------------+

In order to achieve that glorious table I've used these queries (and failed miserably):

SELECT IDsortie, IDadherent 
FROM participe 
ORDER BY IDsortie DESC;

SELECT COUNT(IDsortie) 
FROM participe 
GROUP BY IDadherent 
ORDER BY COUNT(IDadherent) ASC;

SELECT COUNT(IDsortie) 
FROM 
    (SELECT COUNT(*) AS IDsortie 
     FROM participe 
     GROUP BY IDadherent) AS Results

One of the mysql mods has very kindly redirected me to other similar questions but I don't understand their answers, could someone please walk e through this (sorry for the inconvenience).

Gordon Linoff :

It looks like you want a single query:

SELECT IDsortie, COUNT(*) as Numeroadherent
FROM participe 
GROUP BY IDsortie DESC
ORDER BY IDsortie DESC;

I'm not quite sure what your queries have to do with answering the question. Hence, it is unclear what your confusion is. The answer to your question is a simple GROUP BY query.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20448&siteId=1