从WebGrid中的SQL JOIN访问列

时间:2014-05-30 11:54:48

标签: c# razor html-helper

我将在WebGrid中显示一些数据。 SQL语句如下所示:

mSQL = "SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id";

在table1和table2中,我有一些同名的列。如果我想从一个指定的表中访问“重复”列,我习惯(使用Ado)访问它:

[tablename].[columnname]

但这似乎不适用于WebGrid:

var mLocations = mDB.Query(mSQL);
var mGrid = new WebGrid(source: mLocations, rowsPerPage: 50, canPage: true);
mGridHTML = mGrid.GetHtml(
    tableStyle: "grid wide",
    headerStyle: "head",
    alternatingRowStyle: "alt",
    columns: mGrid.Columns(
        mGrid.Column(header: "V_1", format:@item.table1.viewedcount),
        mGrid.Column(header: "V_2", format:@item.table2.viewedcount)
    )
);

我如何访问它们?

1 个答案:

答案 0 :(得分:0)

SELECT语句不会将结果返回到2个单独的查询中。

考虑以下查询

SELECT *
FROM [TableA] A
INNER JOIN [TAbleA] A2
ON A.ID = A2.ID

现在尝试从此查询中选择一列

SELECT Example.ID
FROM
(
    SELECT *
    FROM [TableA] A
    INNER JOIN [TAbleA] A2
    ON A.ID = A2.ID
) Example

无法确定要提取的ID。

所以你必须做类似以下的事情

SELECT Example.ID, Example.ID2
FROM
(
    SELECT A.ID AS ID, A2.ID AS ID2
    FROM [TableA] A
    INNER JOIN [TableA] A2
    ON A.ID = A2.ID
) Example

所以要解决你的问题...

mSQL = "SELECT table1.viewedcount AS table1ViewCount, table2.viewedcount AS table2ViewCount FROM table1 INNER JOIN table2 ON table1.id = table2.id";

...作为您的查询然后设置你的网格......

var mLocations = mDB.Query(mSQL);
var mGrid = new WebGrid(source: mLocations, rowsPerPage: 50, canPage: true);
mGridHTML = mGrid.GetHtml(
    tableStyle: "grid wide",
    headerStyle: "head",
    alternatingRowStyle: "alt",
    columns: mGrid.Columns(
        mGrid.Column(header: "V_1", format:@item.table1ViewCount),
        mGrid.Column(header: "V_2", format:@item.table2ViewCount)
    )
);