1

使用 SQL KATA 进行自联接的正确方法是什么?目前,我只能执行以下操作

var query1 = new Query("Users");
var query = new Query("Users")
    .Join(query1.As("a"), j => j.On("a.Name", "Users.ParentName"))
    .Where("Name", "Sami");

但这会生成以下查询

SELECT
*
FROM
[Users]
INNER JOIN (
    SELECT
    *
    FROM
    [Users]
) AS [a] ON ([a].[Name] = [Users].[ParentName])
WHERE
[Name] = 'Sami'

是否可以实现以下查询?

SELECT
*
FROM
[Users] [a]
INNER JOIN [Users] [b] ON ([a].[ParentName] = [b].[Name])
WHERE
[a].[Name] = 'Sami'
4

1 回答 1

2

无需在这里创建单独的查询实例,就像任何其他表一样。这里的关键是使用table as alias语法来指示 SqlKata 您正在使用不同的别名。

var query = new Query("Users as a")
    .Join("Users as b", "a.ParentName", "b.Name")
    .Where("a.Name", "sami");

这将生成以下 SQL:

SELECT
  *
FROM
  [Users] AS [a]
  INNER JOIN [Users] AS [b] ON [a].[ParentName] = [b].[Name]
WHERE
  [a].[Name] = 'sami'

直接在 Sqlkata Playground 上查看以下示例 Self Join Example on SqlKata Playground

于 2020-04-04T21:00:29.583 回答