How to make a subquery?

You have users in the table, and there is an invite_by_id field that shows the user ID of the person who invited this user. It is necessary for the MySQL query to return rows with all user fields and the invites_count field, showing how many people were invited by each user. Something like that:

SELECT
    User.*, Count.count
FROM
    users AS User,
    (
        SELECT COUNT(*) AS count FROM users WHERE users.invited_by_id=User.id
    ) AS Count;

This one doesn't work, so I need a worker.

+3
source share
2 answers
SELECT  u.*,
        (
        SELECT  COUNT(*)
        FROM    users ui
        WHERE   ui.invited_by_id = u.id
        ) AS cnt
FROM    users u    
+5
source

, , count sql, ( - , ). -, - GROUP BY.

:

SELECT user3.*, subquery.theCount FROM
    users AS user3
INNER JOIN ( 
    SELECT
        user1.id, count(user2.id) AS theCount
    FROM
        users AS user1
    LEFT OUTER JOIN
        users AS user2 ON user2.invited_by_id=user1.id
    GROUP BY user1.id
) AS subquery ON subquery.id=user3.id;

MySQL: GROUP BY , GROUP BY, . RMDMS .

SELECT
    user1.*, count(user2.id) AS theCount
FROM
    users AS user1
LEFT OUTER JOIN
    users AS user2 ON user2.invited_by_id=user1.id
GROUP BY user1.id;
+4

Source: https://habr.com/ru/post/1730411/


All Articles