简体   繁体   English

MySQL - 从双嵌套子查询引用外部表值

[英]MySQL - Referencing outer table value from double nested subquery

The query I really need to execute is follows: 我真正需要执行的查询如下:

SELECT      u.points
        (SELECT COUNT(1) FROM (SELECT 1 FROM checkin c INNER JOIN wineries w ON w.id = c.winery_id WHERE c.user_id = u.id GROUP BY region_id) b) as states_visited
FROM        users u
GROUP BY u.id
ORDER BY points DESC

However, this causes the following error: 但是,这会导致以下错误:

Unknown column 'u.id' in 'where clause' 'where子句'中的未知列'u.id'

I've tried with user-defined variables, no errors, but it's not actually referencing the user-defined variable value for some reason: 我尝试过用户定义的变量,没有错误,但由于某种原因,它实际上并没有引用用户定义的变量值:

SELECT      @uid := u.id, u.points
        (SELECT COUNT(1) FROM (SELECT 1 FROM checkin c INNER JOIN wineries w ON w.id = c.winery_id WHERE c.user_id = @uid GROUP BY region_id) b) as states_visited
FROM        users u
GROUP BY u.id
ORDER BY points DESC

Any thoughts how I can make this work? 有什么想法,我怎么能让这项工作? Without the obvious resorting to doing two separate queries? 没有明显的诉诸两个单独的查询?

Why do you need the double nesting? 你为什么需要双重嵌套? And if the id is the primary key of table user , you don't need the GROUP BY either: 如果id是表user的主键,则不需要GROUP BY

SELECT      u.points,
        (SELECT COUNT(1) FROM reviews WHERE user_id = u.id) AS review_count
FROM        users AS u
-- GROUP BY u.id
ORDER BY points DESC ;

You could also GROUP BY in a derived table - and then join: 您也可以在派生表中进行GROUP BY - 然后加入:

SELECT      u.points,
            COALESCE(r.review_count,0) AS review_count
FROM        users AS u
    LEFT JOIN
        (SELECT user_id, COUNT(1) AS review_count
         FROM reviews
         GROUP BY user_id
        ) AS r
        ON  r.user_id = u.id
ORDER BY points DESC ;

or join and then GROUP BY : 或加入然后GROUP BY

SELECT      u.points,
            COUNT(r.user_id) AS review_count
FROM        users AS u
    LEFT JOIN
            reviews AS r
        ON  r.user_id = u.id
GROUP BY u.id, u.points
ORDER BY points DESC ;

The edited version is harder but can be done without double nesting, too: 编辑后的版本更难,但也可以在没有双重嵌套的情况下完成:

SELECT      u.points,
        (SELECT COUNT(DISTINCT region_id) 
         FROM checkin c INNER JOIN wineries w ON w.id = c.winery_id 
         WHERE c.user_id = u.id 
        ) AS states_visited
FROM        users u
ORDER BY points DESC ;

It seems like you can do what you want with a simpe table join 看起来你可以用simpe表连接做你想做的事

SELECT u.id AS `id`, u.points AS `points`, COUNT(r.review_id) AS `review_count` /* or whatever the id record for reviews table is */
FROM users AS u
INNER JOIN reviews AS r
  ON u.id = r.user_id
GROUP BY `id`
ORDER BY `points` DESC
SELECT users.id, users.points, count(*)
FROM users, reviews
WHERE users.id = reviews.user_id
GROUP BY id,points
ORDER BY points DESC

sqlFiddle example sqlFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM