将两个查询sql合并到一个映射到POCO

时间:2018-08-16 07:42:20

标签: sql

我有两个如下的SQL查询

SELECT ADGroupName, ADGroupDescription, ADGroupEmail
FROM ADGroup 
WHERE ADGroupName = 'XXXX'

这将向我返回有关特定组的信息的单个结果。

SELECT ADUser.ADUserFirstName as FirstName, ADUser.ADUserLastName as 
LastName 
FROM ADUser WHERE ADUser.ADUserName 
IN(SELECT ADUser_ADGroup.ADUGUserName 
FROM ADUser_ADGroup 
WHERE ADUser_ADGroup.ADUGGroupName = 'XXXX_Manager')

这将返回我在上述查询中获得有关信息的组的经理列表。是否可以将两个查询合并为一个sql查询?

整个代码如下

public AdGroupDto GetGroupByGroupName(string groupName)
{
    var sql = "SELECT ADGroupName, ADGroupDescription, ADGroupEmail " +
     "FROM ADGroup " +
     "WHERE ADGroupName = @0";

    var result = _db.Single<AdGroupDto>(sql, groupName);

    var sqlForTeacher = "SELECT ADUser.ADUserFirstName as FirstName, ADUser.ADUserLastName as LastName " +
    "FROM ADUser WHERE ADUser.ADUserName " +
    "IN(SELECT ADUser_ADGroup.ADUGUserName " +
    "FROM ADUser_ADGroup " +
    "WHERE ADUser_ADGroup.ADUGGroupName = @0)";

    var data = _db.Query<UserInfoDto>(sqlForTeacher, groupName + "_Manager").ToList();

   result.Teachers = data;

    return result;
}

Silke-Kruse-ZZA-KL-1A-ZZA-KL-1A类的学生
Sille-达尔-ZZA-KL-1A-ZZA-KL-1A类的学生

2 个答案:

答案 0 :(得分:1)

如果我的表结构正确,并且假设每个表中都有外键,那么应该可以解决以下问题:

ServerDataSource

只需确保为SELECT ADUser.ADUserFirstName AS FirstName, ADUser.ADUserLastName AS LastName, ADGroupName, ADGroupDescription, ADGroupEmail FROM ADUser INNER JOIN ADUser_ADGroup ON ADUser.<id> = ADUser_ADGroup.<user_id> INNER JOIN ADGroup ON ADGroup.<id> = ADUser_ADGroup.<group_id> WHERE ADGroup.ADGroupName = 'XXXX' AND ADUser_ADGroup.ADUGGroupName LIKE '%Manager%' 子句使用特定的列名。

UPD:这是MySQL / MariaDB的代码。

答案 1 :(得分:1)

尝试这个:

SELECT      U.ADUserFirstName as FirstName, U.ADUserLastName as LastName, G.ADGroupName, G.ADGroupDescription, G.ADGroupEmail, 
FROM        ADUser U
INNER JOIN  ADUser_ADGroup UG ON U.ADUserName = UG.ADUGUserName
INNER JOIN  ADGroup G ON UG.ADUGGroupName = G.ADGroupName + '_Manager'
WHERE       G.ADGroupName = 'XXXX'

这会将组名与ADUser_ADGroup后面附加的_Manager进行比较

以上查询是针对SQL Server的。

如果您使用的是Oracle:

SELECT      U.ADUserFirstName as FirstName, U.ADUserLastName as LastName, G.ADGroupName, G.ADGroupDescription, G.ADGroupEmail, 
FROM        ADUser U
INNER JOIN  ADUser_ADGroup UG ON U.ADUserName = UG.ADUGUserName
INNER JOIN  ADGroup G ON UG.ADUGGroupName = G.ADGroupName || '_Manager'
WHERE       G.ADGroupName = 'XXXX'