在where子句结果中使用LEFT JOIN的SELECT表

时间:2014-08-07 06:00:55

标签: mysql sql

以下查询返回:#1054 - 'where子句'中的未知列'word.id'

select * from word,(
SELECT sqrt(variance(ifnull(re_freq,0)))/avg(ifnull(re_freq,0)) cv
FROM pre_cat 
left join (select * from goal where wordid= word.id)g on pre_cat.id= g.catid) gg

我该如何解决?

以下查询返回正确的结果,但只是一个记录!

SELECT  avg(ifnull(re_freq,0)) , variance(ifnull(re_freq,0)),sqrt(variance(ifnull(re_freq,0)))/avg(ifnull(re_freq,0))
FROM pre_cat 
left join (select * from goal where wordid= 9690)g on pre_cat.id= g.catid

并且此查询的结果是:0.500000000375 Upldated架构SQL小提琴 http://sqlfiddle.com/#!2/de6c0/2

我不能为所有结果做到这一点? 请帮帮我!

以下存储过程正常工作,但需要太长时间!

BEGIN
    DECLARE wo_id INT;
    DECLARE num INT;
    DECLARE i INT;
    DECLARE res DOUBLE;
    SELECT COUNT(*) FROM word INTO num;
    SET i=0;
    WHILE i<num DO 
        SELECT  sqrt(variance(ifnull(re_freq,0)))/avg(ifnull(re_freq,0)) FROM pre_cat left join (select * from goal where wordid= i )g on pre_cat.id= g.catid INTO res;
        update word set cv=res where id=i;
        SET i = i + 1;
    END WHILE;
END

2 个答案:

答案 0 :(得分:0)

您的加入语法错误。正如Jens所说,我们不能将外表引用到内部sql中。您可以选择以下

select * from word,(
SELECT sqrt(variance(ifnull(re_freq,0)))/avg(ifnull(re_freq,0)) cv
FROM pre_cat 
left join (select goal.* from goal join word on goal.wordid= word.id)g on pre_cat.id= g.catid) gg

答案 1 :(得分:0)

select * from word join
(SELECT sqrt(variance(ifnull(re_freq,0)))/avg(ifnull(re_freq,0)) cv,
       g.wordid
FROM pre_cat 
left join goal g on pre_cat.id= g.catid
group by g.catid) gg on gg.wordid= word.id

只需通过wordid

将单词表与子查询连接起来