【问题标题】:Natural join in .net自然加入.net
【发布时间】:2012-11-04 05:42:13
【问题描述】:

我正在尝试从 2 个表在 Linq 中进行自然左连接

两张桌子

| questions |
+-----------+
| id        |
| question  |
+-----------+


|  answers  |
+-----------+
|  id       |
|  q_id (fk)|
|  answer   |
+-----------+

我正在尝试为每个问题检索一行,但根据需要使用其他列

我不确定这是否可能

                      ID   | Question   | Answer 1 | Answer 2 | An....
| view      |       |-----------------------------------------------+
+-----------+       |  1   |   question | answer1  | answer2  | ... |
| id        |       |  2   |   question | answer1  | answer2  | ... |
| question  |       |  3   |   question | answer1  | answer2  | ... |
| answer1   |  or   |  4   |   question | answer1  | answer2  | ... |
| answer2   |       |  5   |   question | answer1  | answer2  | ... |
| answer3   |       |  6   |   question | answer1  | answer2  | ... |
| answer... |       |  7   |   question | answer1  | answer2  | ... |
+-----------+       |-----------------------------------------------+

我的 C# Linq

        var joinedTable =
        from questions in db.Results
        join answers in db.Answers on questions.id equals answers.result_id
            into answers
        select new 
        { 
           questions.id, 
           TOTAL_ANSWERS = answers.Count(), 
           questions.SurveyDateCreated, 
           (answers.ForEach(a=> a.answer) as "Answer" + i++)
        };

【问题讨论】:

标签: c# linq join pivot-table


【解决方案1】:

您要查找的内容称为 PIVOT。最好的方法是在 SQL 中创建一个存储过程并在 SQL 中执行 PIVOT。使用 LINQ 是可能的,但很复杂。

使用 LINQ 进行透视: http://madhukap.blogspot.com/2011/05/pivot-with-linq.html http://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多