选择子查询的结果

时间:2014-01-15 15:40:24

标签: mysql sql subquery mysql5

我正在尝试选择q1.res子查询结果的FROM

    (SELECT SUM(gwr.res1)/(COUNT(*)*1000) as 'res' 
     FROM process.gwr 
     WHERE started = 1 AND gwr.user2 = g.id AND gwr.loss = g.id) AS q1

问题是我试图在子查询中选择g.id但由于某种原因它无法访问它而返回错误消息:

[Err] 1054 - Unknown column 'g.id' in 'where clause'

没有任何意义,因为g.id(grand.idid列)

SELECT
    g.name, g.point, g.mx, q1.res
FROM
    (SELECT SUM(gwr.res1)/(COUNT(*)*1000) as 'res' 
     FROM process.gwr 
     WHERE (started = 1) AND (gwr.user2 = g.id) AND (gwr.loss = g.id)) AS q1, grand g
LEFT JOIN process.users p ON (p.id = g.owner)
WHERE
    p.name != ""
ORDER BY
    g.point DESC,
    g.mx DESC
LIMIT 5

问题出在哪里?

2 个答案:

答案 0 :(得分:0)

尝试从子查询中删除''来自'res'。

SELECT
    g.name, g.point, g.mx, q1.res
FROM
    (SELECT SUM(gwr.res1)/(COUNT(*)*1000) as res FROM process.gwr WHERE started = 1 AND gwr.user2 = g.id AND gwr.loss = g.id) AS q1, grand g
LEFT JOIN process.users p ON (p.id = g.owner)
WHERE
    p.name != ""
ORDER BY
    g.point DESC,
    g.mx DESC
LIMIT 5

答案 1 :(得分:0)

您需要提及数据库对象'g'所指的内容。意思是,您需要将“FROM”部分中的表格(或视图)指定为纯交叉引用,或者 - 如果您感觉舒服 - 那么使用某种类型的连接。

e.g

SELECT SUM(gwr.res1)/(COUNT(*)*1000) as 'res' 
FROM process.gwr, process.g 
WHERE started = 1 
    AND gwr.user2 = g.id 
    AND gwr.loss = g.id 

注意'FROM'部分中的'process.g'。

希望有所帮助。

K