简体   繁体   English

如何在MySQL的内部查询中从外部查询访问值

[英]How to access value from outer query in inner query in MySQL

SELECT * FROM events e LEFT JOIN venue v ON v.id=e.venueid 
CROSS JOIN (select (((5*sum(rating = 5))+(4*sum(rating = 4))+(3*sum(rating = 3))+(2*sum(rating = 2))+sum(rating = 1))/count(*)) rating 
from feedbacks where boxid = **e.boxid**) r 
WHERE e.startdate = CURDATE() AND e.starttime >= CURTIME() 
LIMIT 10;

I can't access e.boxid inside the subquery. 我无法访问子查询中的e.boxid Can anybody help? 有人可以帮忙吗?

Another approach to this uses a correlated subquery: 另一种方法使用相关子查询:

SELECT e.*, v.*,
       (SELECT (((5*sum(rating = 5))+(4*sum(rating = 4))+(3*sum(rating = 3))+(2*sum(rating = 2))+sum(rating = 1))/count(*)) as rating 
        FROM feedbacks f
        WHERE f.boxid = e.boxid
       ) as rating
FROM events e LEFT JOIN 
     venue v
     ON v.id = e.venueid 
WHERE e.startdate = CURDATE() AND e.starttime >= CURTIME() 
LIMIT 10;

In this situation, because the WHERE clause filters out many records (presumably), the correlated subquery could be much more efficient than the GROUP BY . 在这种情况下,因为WHERE子句过滤掉了许多记录(可能),相关子查询可能比GROUP BY更有效。 This is especially true if you have an index in feedbacks(boxid) . 如果您在feedbacks(boxid)有索引feedbacks(boxid)则尤其如此。

use a GROUP BY on boxid to bring it outside the subquery and then join it with events table on boxid column like this: boxid上使用GROUP BY将它带到子查询之外,然后将其与boxid列上的events表连接,如下所示:

SELECT 
    *
FROM
    events e
        LEFT JOIN
    venue v ON v.id = e.venueid
        JOIN
    (SELECT 
        boxid,
            (((5 * SUM(rating = 5)) + (4 * SUM(rating = 4)) + (3 * SUM(rating = 3)) + (2 * SUM(rating = 2)) + SUM(rating = 1)) / COUNT(*)) rating
    FROM
        feedbacks
    GROUP BY boxid) r ON e.boxid = r.boxid
WHERE
    e.startdate = CURDATE()
        AND e.starttime >= CURTIME()
LIMIT 10;

You could also use correlated subquery like this: 您还可以使用相关的子查询,如下所示:

SELECT e.*,
  v.*,
  (SELECT (((5*SUM(rating = 5))+(4*SUM(rating = 4))+(3*SUM(rating = 3))+(2*SUM(rating = 2))+SUM(rating = 1))/COUNT(*)) AS rating
  FROM feedbacks f
  WHERE f.boxid = e.boxid
  ) rating
FROM events e
LEFT JOIN venue v
ON v.id           = e.venueid
WHERE e.startdate = CURDATE()
AND e.starttime  >= CURTIME() LIMIT 10;

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

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