itVincent Blog - Java Working Fun!

技术引领时代!
posts - 117, comments - 181, trackbacks - 0, articles - 12
 

"unknown column ... in 'on clause'" in JOIN

 

HQL执行关联查询

1.创建表格:

     CREATE TABLE a (id INT NOT NULL);

     CREATE TABLE b (id INT NOT NULL);

     CREATE TABLE c (a_id INT NOT NULL, b_id INT NOT NULL);

2.HQL语句

    Select (c.id, c.a.id, c.b.id) from C c

        

3.执行查询:

     SELECT (c.id, a.id, b.id) FROM A a, B b LEFT JOIN C c ON c.a_id = a.a_id AND c.b_id = b.b_id

这句话执行应该是没有错误的,但是

Mysql 5 下执行则会出错: "ERROR 1054 (42S22): Unknown column 'a.id' in 'on clause'"

因为mysql下有这样一个BUG,要把联合的表用括号包含起来才行:

    SELECT (c.id, a.id, b.id) FROM (A a, B b) LEFT JOIN C c ON c.a_id = a.a_id AND c.b_id = b.b_id

但是HQL生成就是这样的语句,怎么办呢?我们可以改变HQL的写法来达成生成另一种SQL语句,以避免这种BUG的出错,select (c.id, a.id, b.id) from C c

    Left join c.a a

    Left join c.b b

则会生成

    SELECT (c.id, a.id, b.id) FROM A a LEFT JOIN B b LEFT JOIN C c ON c.a_id = a.a_id AND c.b_id = b.b_id

这样的话mysql下就不会出错了

Feedback

# re: [原创]"unknown column ... in 'on clause'" in JOIN 解疑  回复  更多评论   

2008-08-06 17:59 by hfly
谢谢谢谢!!!!

# re: [原创]"unknown column ... in 'on clause'" in JOIN 解疑  回复  更多评论   

2008-08-27 15:32 by itVincent
不客气,我也没想到mysql有这样一个问题

# re: [原创]"unknown column ... in 'on clause'" in JOIN 解疑  回复  更多评论   

2009-03-12 22:12 by kb
高手。

只有注册用户登录后才能发表评论。


网站导航: