MySQL join on one table

Raphael Jeger

I have a users-table which is like (shorted):

id (BIGINT)
username (VARCHAR)
recommendedByUserId (BIGINT)

In recommendedByUserId the ID of the recommender is stored, which is the users.id-value of the recommender.

Now I need to know how many times each users.id is in users.recommendedByUserId and sort on them descending, so the user with the most recommendations is on top of the result.

I tried:

SELECT u.username, COUNT(r.id) FROM users u INNER JOIN users r ON u.id = r.recommendedByUserId

but that does not work.

juergen d

If the id is sufficient

SELECT recommendedByUserId, COUNT(*) as rec_cnt
FROM users u 
group by recommendedByUserId
order by rec_cnt desc

If you also need the name then you can do

select u.username, x.rec_cnt 
from users u
inner join
(
    SELECT recommendedByUserId as id, COUNT(*) as rec_cnt 
    FROM users u 
    group by recommendedByUserId
) x on x.id = u.id
order by x.rec_cnt desc

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

MySQL, limit one table in join

From Dev

mysql join two table rows in one table

From Dev

MySQL join table return only one match

From Dev

Mysql join table result as one row

From Dev

Mysql : JOIN 2 table , one of the SUM is not correct

From Dev

MySQL JOIN one of the rows from second table

From Dev

Join in MYSQL (Count from One table and list from one table)

From Dev

MYSQL join one colum from one table to two count() in another

From Dev

Mysql Query Join two table Order by one table column

From Dev

MYSQL query SELECT from one table and join results with other table

From Dev

MySQL multiple values join to one table - better query?

From Dev

Join one table to another based on Mysql Case Statement

From Dev

join count from one table to select from another - mysql

From Dev

MySQL, Join two rows from one table and ignore doublons

From Dev

MySQL query: use LIMIT on one table column having an OUTER JOIN

From Dev

MySQL Join query: Two main and one linking table

From Dev

MySQL join 3 tables and find "missing" rows in one table

From Dev

MySQL JOIN - json returns data only from one table

From Dev

One table conditional join

From Dev

mysql - double join (one from same table, one from different table)

From Dev

join one row from one mysql table to multiple row in second table

From Dev

mySQL JOIN on one to many

From Dev

MySQL - How to use (LEFT) JOIN to join two tables via one table together?

From Dev

MySQL - How to use (LEFT) JOIN to join two tables via one table together?

From Dev

Three Table Join MySQL

From Dev

Mysql Table Join on itself

From Dev

mysql Join table

From Dev

MySQL three table join

From Dev

MySQL join three table

Related Related

HotTag

Archive