如何解决未知栏' x.y'在'字段列表'

时间:2014-05-01 23:50:26

标签: mysql sql netbeans

通过Netbeans"执行查询"我在MySQL数据库上运行此查询时出现以下错误:能力。

Error code 1054, SQL state 42S22: Unknown column 'avgratingbyusers.avgrating' in 'field list'
Line 1, column 1

Execution finished after 0 s, 1 error(s) occurred.

从此代码中 教程来源:http://webdam.inria.fr/Jorge/html/wdmch19.html#x25-37800018.4

create table ratings ( 
   userid int, 
   itemid int, 
   rating int, 
   timestamp int, 
   primary key (userid, itemid)); 
create index usersratings_index on ratings (userid); 
create index itemsratings_index on ratings (itemid); 

insert into ratings (userid,itemid,rating,timestamp) 
   (select ratingsdata.userid, ratingsdata.itemid, 
        ratingsdata.rating-avgratingbyusers.avgrating, 
        ratingsdata.timestamp 
    from ratingsdata, 
       (select userid, avg(rating) 
        from ratingsdata 
        group by userid 
       ) as avgratingbyusers 
    where ratingsdata.userid=avgratingbyusers.userid 
   );

我该如何解决这个问题?

编辑---------------------------------------------- ----

尝试将查询更改为此

insert into `ratings` (`userid`,`itemid`,`rating`,`timestamp`) 
 (select `ratingsdata.userid`, `ratingsdata.itemid`, 
    `ratingsdata.rating-avgratingbyusers.avgrating`, 
    `ratingsdata.timestamp `
 from `ratingsdata`, 
   (select `userid`, avg(`rating`) 
    from `ratingsdata`
    group by `userid` 
   ) as `avgratingbyusers`
where `ratingsdata.userid`=`avgratingbyusers.userid`
);

带回蜱。

现在收到以下错误

Error code 1054, SQL state 42S22: Unknown column 'ratingsdata.userid' in 'field list'
Line 1, column 1

Execution finished after 0 s, 1 error(s) occurred.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您需要在子查询中为列提供别名:

insert into ratings (userid,itemid,rating,timestamp) 
   select rd.userid, rd.itemid, rd.rating-ru.avgrating, rd.timestamp 
    from ratingsdata rd join
         (select userid, avg(rating) as avgrating
----------------------------------------^
          from ratingsdata 
          group by userid 
         ) ru 
         on rd.userid = ru.userid ;

重点改变是突出的。我做了其他改动:

  • 删除了select子句周围的括号。对于insert . . . select
  • ,这些是不必要的
  • 更改了连接以使用显式连接而不是隐式连接。
  • 引入了表名称缩写的表别名,以使查询更具可读性。

答案 1 :(得分:0)

似乎这里的减法是不可能的,你可能会在运行代码之前先尝试创建一个avgratingbyusers表;

创建avgratingbyusers

create table avgratingbyusers ( 
   userid int, 
   averating float); 

insert into avgratingbyusers (userid,averating) 
    (select userid, round(avg(rating),4) 
        from ratingsdata 
        group by userid);

通过以下查询获得居中:

create table ratings ( 
   userid int, 
   itemid int, 
   rating int, 
   timestamp int, 
   primary key (userid, itemid)); 
create index usersratings_index on ratings (userid); 
create index itemsratings_index on ratings (itemid); 

insert into ratings (userid,itemid,rating,timestamp) 
   (select ratingsdata.userid, ratingsdata.itemid, ratingsdata.rating-avgratingbyusers.averating, ratingsdata.timestamp 
    from ratingsdata, avgratingbyusers
    where ratingsdata.userid=avgratingbyusers.userid 
   );