今天发现一个奇怪的问题,先看如下SQL语句:
SELECT a.num, b.num, a.depart FROM ( ( SELECT count(depart_Id) AS num, depart_Id AS depart FROM tiku_class GROUP BY depart_id ) a JOIN ( SELECT count(depart_id) AS num, depart_id AS depart FROM tiku_news GROUP BY depart_id ) b ON a.depart = b.depart ) ORDER BY b.num DESC
?直接在MySQL中运行返回如下结果:
?再看在程序中使用Hibernate的:
SQLQuery query = session.createSQLQuery(sql); return query.list();
?的结果:
?可以发现b.num的值等于a.num
太奇怪了吧,打开Hibernate的show_sql选项,将打印的SQL在mysql中执行依然没问题,崩溃。。难道是Hibernate的Bug,没可能啊 ,网上搜索也没发现类似情况。
?
就在百思不得其解的时候,突然看见了这个:
我的SQL代码中明明写的是a.num 和b.num,怎么结果显示的是num 和num1呢?
难道是num 别名相同的原因?
将SQL语句改成这样:
SELECT a.numa, b.numb AS numb, a.depart FROM ( ( SELECT count(depart_Id) AS numa, depart_Id AS depart FROM tiku_class GROUP BY depart_id ) a JOIN ( SELECT count(depart_id) AS numb, depart_id AS depart FROM tiku_news GROUP BY depart_id ) b ON a.depart = b.depart ) ORDER BY numb DESC
?
?再次运行程序,Oh Yes!这次结果终于正确了!
?
具体原因目前还说不清楚,但是以后写SQL语句起别名还是要注意些啊,尽量不要起一样的别名啊
?