如何选择只有一个不同列的多列来连接两个具有所有id的表是使用Nhibernate的UNIQUEIDENTIFIER

时间:2017-07-05 07:52:42

标签: c# mysql sql nhibernate

以下是我的表结构:

create table Department(
    deptid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Department_P_KEY PRIMARY KEY,
    departmentname varchar(100)
    )

create table Employee(
    empid [UNIQUEIDENTIFIER] ROWGUIDCOL DEFAULT NEWSEQUENTIALID() NOT NULL CONSTRAINT Employee_P_KEY PRIMARY KEY,
    name varchar(50), 
    city varchar(50),     
    deptid UNIQUEIDENTIFIER NOT NULL,
    foreign key(deptid) references Department(deptid) ON DELETE CASCADE ON UPDATE CASCADE
    )

我的问题是,当我选择mutliple列并在一列上应用DISTINCT时,所有主键和外键都是UNIQUEIDENTIFIER,那么该时间查询会给出错误消息。我的查询和错误如下:

select distinct(Department.deptid),min(Employee.empid) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid

和错误消息是:

  

消息8117,级别16,状态1,行2操作数数据类型uniqueidentifier对于min运算符无效。

但是如果主键和外键是int,则上面的查询将成功执行,因为min函数支持整数但是如何使用uniqueidentifier键选择不同的记录。

以下是我的Nhibernate查询: -

EmployeeEntity employeeEntity = new EmployeeEntity();
            employeeEntity.DepartmentMaster = new DepartmentEntity();
            ProjectionList projectionList = Projections.ProjectionList();
            projectionList.Add(Projections.Distinct(Projections.Property<EmployeeEntity>(x => x.DepartmentMaster)).WithAlias(() => employeeEntity.DepartmentMaster));
            projectionList.Add(Projections.Property<EmployeeEntity>(x => x.empid).WithAlias(() => employeeEntity.empid));

            IList<EmployeeEntity> query = null;
            query = NHSession.QueryOver<EmployeeEntity>()
            .Select(projectionList)
            .TransformUsing(Transformers.AliasToBean<EmployeeEntity>()).List<EmployeeEntity>();

如何按照上面的sql查询首先在sql中执行不同的查询?。

1 个答案:

答案 0 :(得分:1)

只需将UniqueIdentifier转换为字符串

即可
select distinct(Department.deptid),min(CAST(Employee.empid AS NVARCHAR(36))) as empid
from Employee
inner join Department on Department.deptid = Employee.deptid
group by Department.deptid