gpt4 book ai didi

sql - Nhibernate count distinct(基于多列)

转载 作者:行者123 更新时间:2023-12-04 13:33:18 28 4
gpt4 key购买 nike

基本上,我一直在尝试这样做(基于两列计算不同):

select count(distinct(checksum(TableA.PropertyA, TableB.PropertyB))) 
from TableA
left outer join TableB
on TableA.TableBId = TableB.Id
where PropertyA like '%123%'

一直在谷歌上搜索如何做到这一点,但没有运气。试过这个,但从未真正奏效。根据两个表中的两个属性,这并不能明确计算:
var queryOver = c.QueryOver<TableA>();
TableB tableBAlias = null;
TableA tableAAlias = null;
ProjectionList projections = Projections.ProjectionList();

queryOver.AndRestrictionOn(x => x.PropertyA).IsLike("%123%");
projections.Add(Projections.CountDistinct(() => tableAAlias.PropertyA));

queryOver.JoinAlias(x => x.TableB , () => tableBAlias, JoinType.LeftOuterJoin);
projections.Add(Projections.CountDistinct(() => tableBAlias.PropertyB));

queryOver.Select(projections);
queryOver.UnderlyingCriteria.SetProjection(projections);
return queryOver.TransformUsing(Transformers.DistinctRootEntity).RowCount();

最佳答案

好的,这将采取一些步骤,所以请耐心等待。我在这里假设 SQL 服务器,但说明应该适用于任何支持 checksum 的方言。 1:

  • 创建支持 checksum 的自定义方言功能:

    public class MyCustomDialect : MsSql2008Dialect
    {
    public MyCustomDialect()
    {
    RegisterFunction("checksum", new SQLFunctionTemplate(NHibernateUtil.Int32, "checksum(?1, ?2)"));
    }
    }
  • 更新您的配置以使用自定义方言(您可以在配置 XML 文件或代码中执行此操作。请参阅 this answer 了解更多信息)。以下是我在现有配置代码中的操作方式:

    configuration
    .Configure(@"hibernate.cfg.xml")
    .DataBaseIntegration(
    db => db.Dialect<MyCustomDialect>());
  • 创建调用 checksum 的自定义投影.这一步是可选的——您可以调用Projections.SqlFunction如果您愿意,可以直接使用,但我认为将其重构为单独的函数会更简洁:

    public static class MyProjections 
    {
    public static IProjection Checksum(params IProjection[] projections)
    {
    return Projections.SqlFunction("checksum", NHibernateUtil.Int32, projections);
    }
    }
  • 编写 QueryOver 查询并调用自定义投影:

    int count = session.QueryOver<TableA>(() => tableAAlias)
    .Where(p => p.PropertyA.IsLike("%123%"))
    .Left.JoinQueryOver(p => p.TableB, () => tableBAlias)
    .Select(
    Projections.Count(
    Projections.Distinct(
    MyProjections.Checksum(
    Projections.Property(() => tableAAlias.PropertyA),
    Projections.Property(() => tableBAlias.PropertyB)))))
    .SingleOrDefault<int>();

    这应该生成看起来像您所追求的 SQL:

    SELECT count(distinct checksum(this_.PropertyA, tableba1_.PropertyB)) as y0_
    FROM [TableA] this_
    left outer join [TableB] tableba1_
    on this_.TableBId = tableba1_.Id
    WHERE this_.PropertyA like '%123%' /* @p0 */

  • 1仍在尝试弄清楚是否有一种方法可以在不手动指定参数数量的情况下映射函数

    关于sql - Nhibernate count distinct(基于多列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21725327/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com