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

时间:2017-01-28 10:58:01

标签: mysql sql

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;

我无法访问子查询中的 e.boxid 。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

另一种方法是使用相关子查询:

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;

在这种情况下,因为WHERE子句过滤掉了许多记录(可能),相关子查询可能比GROUP BY更有效。如果您在feedbacks(boxid)中有索引,则尤其如此。

答案 1 :(得分:1)

使用GROUP BY上的boxid将其带到子查询之外,然后将其与events列上的boxid表一起加入,如下所示:

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;

您还可以使用相关的子查询:

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;