Search code examples
c#sqlkata

SQLKata Multiple From Sub Selects


I am trying to write the following statement is my desired output:

SELECT TABLE1.COLUMN_1
  FROM (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE1,
       (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE2
 WHERE TABLE1.COLUMN_1 = TABLE2.COLUMN_1;

This is the code SQLKata:

<PackageReference Include="SqlKata" Version="3.2.3" />
<PackageReference Include="SqlKata.Execution" Version="3.2.3" />

using SqlKata;
using SqlKata.Execution;

var q1= new Query("DUAL").Select("'0' AS COLUMN_1");
var q2= new Query("DUAL").Select("'0' AS COLUMN_1");
var q3= new Query().From(q1, "table1")
                   .From(q2, "table2")
                   .Where("table1.COLUMN_1","table2.COLUMN_1")
                   .Select("table1.COLUMN_1")
                   .FirstOrDefault<string>();

This results in:

SELECT TABLE1.COLUMN_1
  FROM (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE2
 WHERE TABLE1.COLUMN_1 = TABLE2.COLUMN_1;

It looks like it the second From overwrites the first from.

Another example:

var phones = new Query("Phones");
var laptops = new Query("Laptops");

var query = new Query().From(phones, "P").From(laptops, "L") 

Results, notice Phones is not in the query:

SELECT
  *
FROM
  (
    SELECT
      *
    FROM
      [Laptops]
  ) AS [L]

Solution

  • This is basically an inner join query, so you can rewrite it like this one:

    SELECT TABLE1.COLUMN_1
      FROM (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE1 JOIN
           (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE2
     ON TABLE1.COLUMN_1 = TABLE2.COLUMN_1;
    

    and this is the equivalent syntax in SqlKata

    var q1 = new Query("DUAL").Select("'0' AS COLUMN_1");
    var q2 = new Query("DUAL").Select("'0' AS COLUMN_1");
    
    var query = new Query()
        .From(q1, "table1")
        .Join(
            q2.As("table2"), // note how the As() method is used to alias this sub query 
            j => j.On("table1.COLUMN_1","table2.COLUMN_1")
        )
        .Select("table1.COLUMN_1");