如何从两个表中获取数据?

时间:2012-08-18 00:47:28

标签: postgresql java

我正在使用Hibernate和PostgreSql。在hibernate中我有两个类,如:

Mobile(id, name, serial no,model_no)
Model(id, description, value)

现在,Model类的值存储在Mobile类(model_no)中。此Mobile类没有对Model类的任何引用。

在Model类中有如下数据:

Modal
======
id description value
1  aaaa        1
2  bbbbb       2
3  ccccc       3
4  ddddd       12
5  eeee        40

此处此值存储在Mobile表中。在Mobile表中,我将model_no设置为0(不在Model中,我不想将该值放在Model表中,因为如果我放了我需要更改很多代码。

现在我想要一个查询来获得像

这样的输出
value description
----   ------------
0     UNKNOWN
1     aaaa
2     bbbbb
3     ccccc
4     ddddd
5     eeee.
像这样。为了获得全部model_nos,我可以使用像

这样的查询
select modal_no from Mobile 
where modal_no in(select value from Modal) or model_no = 0

但是在这里我的描述也在Model表中。有人可以帮忙吗?


感谢你兄弟的回复,因为我提到过这个移动表(Hibernate Mobile类)没有引用Model表(在hibernate Model类中)。如果我参考了移动课程中的模型,那么您的答案将是100%正确的。在我的Mobile类中,此model_no是整数值。如果我在hql中使用您的查询,我将得到像“path expected”这样的异常。我希望Hql(或sql)查询获得0值的输出。 我的hibernate Mobile类就像这样

 class Mobile { 
   int id;   
   int model_no; // this model_no has 0 + modal_no values(1,2,3,12,42). 
   // some references like 
   Manufacture manf; 
   SerialNo serialno;
   Customer cust; 

  getters and setters 
}

我的Hibernate Model类就像......

class Model{
   int id;
   String description;
   int value; this column has 1,2,3,12,42. it don't have 0.

   setters and getters.
}

1 个答案:

答案 0 :(得分:2)

left join可以实现:

select  Mobile.modal_no 
,       Modal.description
from    Mobile 
left join    
        Modal
on      Mobile.model_no = Modal.value
相关问题