【问题标题】:How to query a bag with Nhibernate如何使用 Nhibernate 查询包
【发布时间】:2010-12-20 17:17:21
【问题描述】:

我需要获取国家列表中不包含国家/地区的出版物(IsoCode2 研究)

sql查询是:

select * from pub_head ph
where not exists
(select 1 from pub_head_forbidden_country phfc , country c
                where phfc.pub_head_id = ph.pub_head_id 
                and phfc.country_id = c.country_id 
                and c.iso_code2 = 'CA');

还有型号:

<class name="Publication" table="PUB_HEAD">

  <id name="Id" column="PUB_HEAD_ID">
   <generator class="native">
    <param name="sequence">SEQ_PUB_HEAD</param>
   </generator>
  </id>

  <idbag name="Countries" table="PUB_HEAD_COUNTRY" lazy="true">
   <collection-id column="PUB_HEAD_COUNTRY_ID">
    <generator class="native">
     <param name="sequence">SEQ_PUB_HEAD_COUNTRY</param>
    </generator>
   </collection-id>

   <key column ="PUB_HEAD_ID"  />
   <many-to-many class="Model.Referential.Country, Model" column="COUNTRY_ID"/>
  </idbag>
</class>

<class name="Country" table="Country">
  <id name="Id" column="COUNTRY_ID">
   <generator class="native">
   </generator>
  </id>
  <property name="Name">
   <column name="NAME"></column>
  </property>
  <property name="IsoCode2">
   <column name="ISO_CODE2"></column>
  </property>
  <property name="IsoCode3">
   <column name="ISO_CODE3"></column>
  </property>

 </class>

我从子查询开始,但没有成功。

谢谢

【问题讨论】:

  • 你想在 hql 中查询还是使用条件 api 进行查询?您发布的 sql 查询中的 pub_head_forbidden_​​country 表是什么?
  • pub_head_forbidden_​​country 表类似于 pub_head_country 表(抱歉复制/粘贴)
  • 我没有在您的模型中看到 pub_head_forbidden_​​country 映射。如果它没有被映射,你就不能使用 NHibernate 来查询它。您是说您有一个从示例中省略的 Publication.ForbiddenCountries 集合吗?

标签: c# nhibernate many-to-many subquery


【解决方案1】:

Sql也可以这样

SELECT * FROM pub_head ph
WHERE ph.pub_head_id not IN (
  SELECT phfc.pub_head_id
  FROM pub_head_forbidden_country phfc
    INNER JOIN country  c ON phfc.country_id = c.country_id
  WHERE c.iso_code2 = 'CA'
)

【讨论】:

    【解决方案2】:

    对连接过敏?那个 SQL 很难理解。

    是这个意思吗?

    SELECT *
    FROM pub_head
    WHERE id not IN (
      SELECT phfc.pub_head_id
      FROM pub_head_forbidden_country as phfc
        INNER JOIN country AS c ON phfc.country_id = c.country_id
      WHERE c.iso_code2 = 'CA'
    )
    

    [作为答案发布,因为这条 SQL 在评论中会很糟糕。]

    【讨论】:

    • 是的,我对连接过敏 ;)
    • 这样的查询不是更语义化,更不容易混淆吗?或者也许我的大脑只是虚弱和懒惰。 :) [顺便说一句:我会尝试回答,但我不知道如何解决您的问题。]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多