Referencing outer query's tables in a subquery

前端 未结 5 1100
太阳男子
太阳男子 2020-12-14 05:20

Is it possible to reference an outer query in a subquery with MySQL? I know there are some cases where this is possible:

SELECT *
FROM table t1
WHER         


        
相关标签:
5条回答
  • 2020-12-14 06:09

    Isn't this what you're after?

    SELECT u.username, c._postCount
    FROM User u
    INNER JOIN (
        SELECT p.user, COUNT(*) AS _postCount
        FROM Posting p
        GROUP BY p.user    
    ) c ON c.user = u.id
    WHERE u.joinDate < '2009-10-10';
    

    The reason this will work is that the nature of the join itself will filter on user. You don't need to have a WHERE clause explictly filtering on user.

    0 讨论(0)
  • 2020-12-14 06:17

    This would work fine

    SELECT u.id as userid,u.username, c._postCount
    FROM User u
    INNER JOIN (
        SELECT p.user, COUNT(*) AS _postCount
        FROM Posting p
        --# This is the reference I would need:
        WHERE p.user = userid
        GROUP BY p.user
    ) c ON c.user = u.id
    WHERE u.joinDate < '2009-10-10';
    
    0 讨论(0)
  • 2020-12-14 06:20

    This solution is for postgresql. You could use LATERAL JOIN which is available in postgresql. Here is how you could use it in your query.

    SELECT u.username, c._postCount
    FROM User u
    INNER JOIN LATERAL (
        SELECT p.user, COUNT(*) AS _postCount
        FROM Posting p
        WHERE p.user = u.id
        GROUP BY p.user
    ) c ON c.user = u.id
    WHERE u.joinDate < '2009-10-10';
    

    Here is a reference you could use. https://medium.com/kkempin/postgresqls-lateral-join-bfd6bd0199df

    0 讨论(0)
  • 2020-12-14 06:21

    This is probably better:

    SELECT u.username,
    (SELECT COUNT(*) FROM Posting WHERE user = u.id) as _postCount
    FROM User u WHERE u.joinDate < '2009-10-10';
    
    0 讨论(0)
  • 2020-12-14 06:24

    i think that won't work, because you're referencing your derived table 'c' as part of a join.

    however, you could just take out the WHERE p.user = u.id though and replace with a GROUP BY p.user in the derived table, because the ON c.user = u.id will have the same effect.

    0 讨论(0)
提交回复
热议问题