"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下就不会出错了